CollectionsChapter 25 of 114
List Access
Get items out by position, from either end, and in slices.
Indexing from zero
The first item is at 0. This trips everyone up once and then never again:
names = ["Ada", "Grace", "Katherine"]
print(names[0])
print(names[2])Output
Ada Katherine
The last valid index is len(names) - 1. Going past it is an error:
names = ["Ada", "Grace", "Katherine"]
try:
print(names[3])
except IndexError as problem:
print("IndexError:", problem)Output
IndexError: list index out of range
Counting from the right
Negative indexes save the arithmetic:
names = ["Ada", "Grace", "Katherine"]
print(names[-1])
print(names[-2])Output
Katherine Grace
names[-1] is the standard way to say "the last one".
Slices
The same start, stop and step as strings. The result is a new list:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[::2])
print(numbers[::-1])Output
[1, 2, 3] [0, 1, 2] [3, 4, 5] [0, 2, 4] [5, 4, 3, 2, 1, 0]
Slices never raise on out-of-range positions, which makes them safe on input you have not measured:
numbers = [1, 2, 3]
print(numbers[0:99])
print(numbers[10:20])Output
[1, 2, 3] []
A slice is a copy
This matters. Changing a slice does not touch the original:
original = [1, 2, 3]
piece = original[0:2]
piece[0] = 99
print(piece)
print(original)Output
[99, 2] [1, 2, 3]
It is a shallow copy, which is a distinction the copy chapter comes back to.
Unpacking
When you know the length, unpacking reads better than indexing:
point = [4, 9]
x, y = point
print(x, y)
first, *rest = [1, 2, 3, 4]
print(first, rest)Output
4 9 1 [2, 3, 4]
Finding a position
index() gives the first position of a value, and raises if there is none:
names = ["Ada", "Grace", "Ada"]
print(names.index("Ada"))
print(names.count("Ada"))Output
0 2
Test yourself
2 questionsFor names = ["Ada", "Grace"], what is names[2]?
Show the answer
An IndexError — The last valid index is len - 1. Use names[-1] for the last item.
What does [1, 2, 3][10:20] give?
Show the answer
An empty list — Slices never raise on out-of-range positions. Only indexing does.
Change Items
Replace one item or a whole slice, in place.