Python Access List Items
An index is the position number of an item in a list. The first item sits at position 0.
Pick one item by index
The index goes in square brackets after the list name.
temps = [18, 20, 22, 21, 23, 25, 24]
print(temps[0])
print(temps[2])Count from the end
Negative indexes count backwards. The last item is -1.
temps = [18, 20, 22, 21, 23, 25, 24]
print(temps[-1])
print(temps[-2])Slice out a part
A slice gives you a new list. The first list stays unchanged.
temps = [18, 20, 22, 21, 23, 25, 24]
print(temps[0:3])
print(temps)Check with in
The in operator answers True or False.
temps = [18, 20, 22, 21, 23, 25, 24]
print(22 in temps)
print(30 in temps)A bad index fails
This list has indexes 0, 1, and 2 only. Index 7 does not exist, so Python stops with an error.
temps = [18, 20, 22]
print(temps[7])Example
temps = [18, 20, 22, 21, 23, 25, 24]
print("First day:", temps[0])
print("Last day:", temps[-1])
print("Weekend:", temps[5:7])Key points
- Index: the position number of an item in a list, starting at 0
- Use my_list[0] for the first item and my_list[-1] for the last item
- Slice: a piece cut from a list, such as temps[0:3]
- A slice is a new list.
- A slice includes the start index.
- It stops before the end index.
- Use in to ask if a value is in a list, such as 22 in temps
- A slice past the end is safe.
- It just stops at the last item.
- Strings use the same index rules.
In this example, temps holds seven temperatures, Monday first. temps[0] picks the first item, 18. temps[-1] picks the last item, 24. The slice temps[5:7] picks indexes 5 and 6. Those are Saturday and Sunday, so the weekend prints as a new list.
Note
Picking one item past the end raises IndexError.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does colors[-2] give for colors = ["red", "green", "blue"]?