Understanding List Indexing
Python lists are a powerful data structure that allow you to store and manipulate collections of items. Each item in a list is assigned a unique index, which is an integer value that represents the position of the item within the list.
Accessing List Elements
To access an element in a list, you use the index of the element enclosed in square brackets []
. For example:
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) ## Output: 'apple'
print(my_list[1]) ## Output: 'banana'
print(my_list[2]) ## Output: 'cherry'
In Python, list indices start from 0, so the first element is at index 0, the second element is at index 1, and so on.
Negative Indexing
Python also supports negative indexing, which allows you to access elements from the end of the list. The index -1 refers to the last element, -2 refers to the second-to-last element, and so on.
my_list = ['apple', 'banana', 'cherry']
print(my_list[-1]) ## Output: 'cherry'
print(my_list[-2]) ## Output: 'banana'
print(my_list[-3]) ## Output: 'apple'
List Slicing
In addition to accessing individual elements, you can also use slicing to extract a subset of elements from a list. Slicing is done using the colon :
operator, and it allows you to specify a start index, an end index (exclusive), and an optional step size.
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(my_list[1:4]) ## Output: ['banana', 'cherry', 'date']
print(my_list[::2]) ## Output: ['apple', 'cherry', 'elderberry']
print(my_list[::-1]) ## Output: ['elderberry', 'date', 'cherry', 'banana', 'apple']
Understanding list indexing is crucial for effectively working with lists in Python. By mastering the concepts of positive and negative indexing, as well as list slicing, you'll be able to navigate and manipulate lists with ease.