Sub topic 8
Getting index and value with enumerate()
This chapter assumes you can write a basic for loop, know how range() and len() work, and can unpack a tuple into two variables. It covers enumerate(), the built-in that gives you each item together with its position.
The problem with range(len(...))
Sometimes you need both the position and the value of each item. The index-based way uses range(len(...)) and then looks each item up by index.
names = ["Ada", "Grace", "Linus"]
for i in range(len(names)):
print(i, names[i])This works, but it has costs. You write names twice, so renaming it means editing two places. You must index into the list on every pass. It also fails for iterables that cannot be indexed, such as files, generators, and sets.
The enumerate() solution
enumerate(iterable) wraps any iterable and yields pairs of (index, item). Python unpacks each pair into two loop variables.
names = ["Ada", "Grace", "Linus"]
for i, name in enumerate(names):
print(i, name)The output is the same as before, and the intent is clearer. The loop never touches the list by index, so the loop body cannot hit an IndexError from a wrong bound.
Choosing the starting number
The counter starts at 0 by default. Pass start to begin elsewhere. This is useful for numbered output meant for people, who usually count from 1.
for number, name in enumerate(["Ada", "Grace", "Linus"], start=1):
print(f"{number}. {name}")This prints 1. Ada, 2. Grace, and 3. Linus. The start value only changes the counter. It does not skip any items, and it is not an index into the original list.
Combining enumerate() with zip()
When you loop over several iterables at once, wrap the zip() call in enumerate(). The pair from zip() must be in its own parentheses so Python unpacks it correctly.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(rank, name, score)The structure rank, (name, score) mirrors the data: enumerate yields (rank, (name, score)).
What enumerate() really yields
An enumerate object is an iterator. Each step produces an ordinary tuple, so you can also keep the pair whole.
pairs = list(enumerate("abc"))
print(pairs) # [(0, 'a'), (1, 'b'), (2, 'c')]Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `for i, x in enumerate(items, 1)` then `items[i]` | Off-by-one item or `IndexError` | Use `items[i - 1]`, or keep the default start |
| `for i in enumerate(items)` | `i` is a whole tuple, such as `(0, 'a')` | Unpack with `for i, x in ...` |
| `enumerate(items, start)` with a float | `TypeError` | Pass an integer |
| Using `range(len(x))` only to print `x[i]` | Works, but is noisy | Use `enumerate(x)` |
range(len(...)) is still the right tool when you need the index alone, for example to assign into a list by position or to step through two lists whose lengths you compare.
Exercise
Write a loop that prints each line of ["red", "green", "blue"] as "1: red", "2: green", "3: blue" using enumerate().
Show answer
for n, color in enumerate(["red", "green", "blue"], start=1): print(f"{n}: {color}")
Exercise
What does list(enumerate(["x", "y"], start=10)) return?
Show answer
[(10, 'x'), (11, 'y')]. The counter starts at 10, and both items are still included.