Accessing List Items
Once you have a list, you need to get items out of it. You do this using indexes — numbers that identify each item's position.
Indexing Starts at Zero
In programming, counting starts at 0, not 1. The first item is at index 0, the second at index 1, and so on:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
print(fruits[3]) # date
This zero-based indexing feels strange at first but becomes natural with practice. Think of the index as "how many positions from the start" — the first item is zero positions from the start.
Negative Indexing
Python has a clever shortcut for accessing items from the end: negative indexes. -1 is the last item, -2 is second-to-last, and so on:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[-1]) # date (last)
print(fruits[-2]) # cherry (second to last)
This is much cleaner than calculating fruits[len(fruits) - 1] every time you want the last item.
Slicing: Getting Multiple Items
Sometimes you want a portion of a list, not just one item. Slicing extracts a range:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry', 'date']
The slice [1:3] means "from index 1 up to (but not including) index 3." The start is inclusive, the end is exclusive.
Leaving out the start ([:2]) means "from the beginning." Leaving out the end ([2:]) means "to the end."
What Happens With Invalid Indexes?
If you try to access an index that doesn't exist, Python raises an IndexError:
fruits = ["apple", "banana", "cherry"]
print(fruits[10]) # IndexError: list index out of range
This is Python telling you the list isn't that long. Always be mindful of your list's length when accessing by index.
Checking List Length
Use len() to find how many items a list contains:
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
Since indexing starts at 0, the valid indexes for a list of length 3 are 0, 1, and 2.