List Indexing
What is List Indexing?
List indexing is a feature in Python that enables us to access individual items in a list based on their position, or index, within the list. Index numbers start from 0 for the first element.
Consider this list:
The index of ‘Sherlock Holmes’ is 0, ‘To Kill A Mockingbird’ is 1, and so on.
To access a list item, Python uses this syntax:
Negative Indexing
Python also supports negative indexing. This starts from the end of the list with -1 referring to the last item, -2 referring to the second last item, and so on.
Modifying List Items through Indexing
List indexing can also be used to modify items within a list.
In the above code, ‘Sherlock Holmes’ is replaced by ‘Pride and Prejudice’.
Did you know?
Python will throw an IndexError
if you try to access or modify a list item at an index that does not exist.
List indexing is a fundamental concept in Python and forms the basis for more advanced topics like list slicing and iterations.