5.8 Accessing the elements of a List (BT101CO)
Accessing elements in a list is done through Indexing. In Python, every item in a list has a specific position, and Python allows you to count these positions from both the beginning and the end of the list.
1. Positive Indexing (Starting from 0)
Python uses zero-based indexing. The first element is at index 0, the second at index 1, and so on.
Syntax: list_name[index]
fruits = ["Apple", "Banana", "Cherry", "Date"]
print(fruits[0]) # Output: Apple
print(fruits[2]) # Output: Cherry
2. Negative Indexing (Starting from -1)
Negative indexing allows you to access items from the end of the list without knowing its total length. -1 refers to the last item, and -2 refers to the second-to-last item.
fruits = ["Apple", "Banana", "Cherry", "Date"]
print(fruits[-1]) # Output: Date
print(fruits[-3]) # Output: Banana
3. Accessing Nested Lists
If a list contains another list (a nested list), you use multiple square brackets to "drill down" into the data.
matrix = [[1, 2], [3, 4], [5, 6]]
# Access the second list [3, 4]
sub_list = matrix[1] # Output: [3, 4]
# Access the number '4' inside that list
number = matrix[1][1] # Output: 4
The "IndexError"
If you try to access an index that doesn't exist (e.g., fruits[10] when the list only has 4 items), Python will raise an IndexError: list index out of range. Always ensure your index is less than the len(list_name).