Sub topic 10
Iterators are used up: pitfalls to avoid
This chapter assumes you can write for loops over lists, unpack tuples in a loop header, and use enumerate and zip for basic cases. Here you will learn why both functions return objects that can be read only once, and how to avoid the bugs this causes.
Lazy, one-shot results
Calling enumerate(...) or zip(...) does not build a list of pairs. It returns an iterator, an object that produces the next item each time something asks for one. Each item is created on demand and then forgotten. This saves memory, because a zip over two huge inputs never holds all the pairs at once.
The trade-off is that an iterator moves in one direction only. After it has produced its last item, it is exhausted and stays empty.
pairs = zip([1, 2, 3], ["a", "b", "c"])
print(list(pairs))
# [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(pairs))
# []The second list(pairs) returns an empty list. Python raises no error, which makes this bug easy to miss.
A list behaves differently. A list is an iterable: each for loop over it asks for a fresh iterator, so you can loop over it as many times as you like. An iterator is its own iterator. Looping over it a second time continues from where the first loop stopped, and that place is the end.
diagram mermaid
caption: Life of a zip iterator across two passes
alt: A state diagram showing a zip iterator moving from Created to Partly consumed to Exhausted, and staying Exhausted on any later pass.
stateDiagram-v2
[*] --> Created: zip(a, b)
Created --> PartlyConsumed: first next()
PartlyConsumed --> PartlyConsumed: more next()
PartlyConsumed --> Exhausted: no items left
Exhausted --> Exhausted: later passes get nothingCommon pitfalls
Looping twice over the same iterator
The most frequent mistake is storing a zip or enumerate result in a variable and using it in two loops.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
rows = zip(names, scores)
for name, score in rows:
print(name, score)
for name, score in rows:
print("again:", name, score) # never runsThe second loop prints nothing. There are two fixes. The simplest is to build the iterator again where you need it. The other is to store the pairs in a list once, which costs memory but allows repeated passes.
rows = list(zip(names, scores))
for name, score in rows:
print(name, score)
for name, score in rows:
print("again:", name, score)Checking length or indexing
Iterators have no length and cannot be indexed. Both lines below fail with TypeError.
rows = zip([1, 2, 3], ["a", "b", "c"])
try:
print(len(rows))
except TypeError as error:
print(error)
try:
print(rows[0])
except TypeError as error:
print(error)Convert to a list first if you need len() or [...].
Testing truthiness
An iterator object is always truthy, even when it has nothing left. This check never detects an empty zip:
empty = zip([], [])
if empty:
print("always printed, even though empty")
if not list(empty):
print("this is the reliable emptiness test")Converting to a list for the test consumes the iterator, so do it only when you no longer need the original object.
Consuming a value by peeking
Calling next() on an iterator, or passing it to list(), sum(), max(), sorted(), or in, uses up items. A partial read leaves the rest for the next reader.
indexed = enumerate(["a", "b", "c"])
first = next(indexed)
print(first)
# (0, 'a')
for index, letter in indexed:
print(index, letter)
# 1 b
# 2 cThe loop starts at index 1 because item 0 was already taken. This can be useful, for example to skip a header row, but it is a bug when you did not intend it.
Reusing one iterator in two places
Because a for loop on an iterator continues where it stopped, passing the same iterator into two consumers splits the data between them.
pairs = zip([1, 2, 3, 4], "abcd")
total = sum(number for number, _ in pairs)
letters = [letter for _, letter in pairs]
print(total)
# 10
print(letters)
# []The first line consumes everything, so the second finds nothing.
Choosing between an iterator and a list
| Situation | Better choice |
|---|---|
| One pass in a `for` loop | Use the iterator directly |
| Very large inputs, one pass | Use the iterator directly |
| Need to loop more than once | `list(zip(...))` or call `zip` again |
| Need `len()`, indexing, or slicing | `list(...)` first |
| Need to print or inspect while debugging | `list(...)` on a copy, or rebuild it |
Summary of rules
- Treat the result of
enumerateandzipas single-use. - Write the call directly in the
forheader when you need one pass. - Turn it into a list when you need repeated passes, a length, or indexing.
- Remember that
list(),sum(),next(), and similar calls all use up items.
Exercise
This code prints the totals but then prints an empty list for the names. Explain why, and change one line so both outputs are correct. pairs = zip(["x", "y", "z"], [1, 2, 3]) print(sum(value for , value in pairs)) print([name for name, in pairs])
Show answer
The first line consumes the zip iterator completely, so the list comprehension on the second line finds no items and returns []. Fix it by storing the pairs in a list: pairs = list(zip(["x", "y", "z"], [1, 2, 3])). The sum is then 6 and the names are ['x', 'y', 'z'].
Exercise
You call rows = enumerate(["a", "b", "c"]) and then next(rows). What does the following for index, letter in rows: loop print as its first index, and why?
Show answer
Its first index is 1. The call to next(rows) already took the pair (0, 'a'), and the loop continues from the next unread item, (1, 'b').