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:

1books = ['Sherlock Holmes', 'To Kill A Mockingbird', '1984', 'The Alchemist', 'The Catcher in the Rye']

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:

1print(books[0])    # prints 'Sherlock Holmes'
2print(books[1])    # prints 'To Kill A Mockingbird'

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.

1print(books[-1])    # prints 'The Catcher in the Rye'
2print(books[-2])    # prints 'The Alchemist'

Modifying List Items through Indexing

List indexing can also be used to modify items within a list.

1books[0] = 'Pride and Prejudice'
2print(books)    # prints ['Pride and Prejudice', 'To Kill A Mockingbird', '1984', 'The Alchemist', 'The Catcher in the Rye']

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.