Sub topic 10
Iterators are used up: pitfalls to avoid
This chapter covers what happens when you use an enumerate or zip result more than once, and the related bugs that come from the same cause. It assumes you can already write for loops over lists, unpack tuples in a loop header, and use enumerate and zip in simple cases. It also assumes you know that for calls iter() on its input.
What enumerate and zip actually return
Calling enumerate(items) or zip(a, b) does not build a list of pairs. It returns a small object that produces pairs on demand, one per request. Such an object is an iterator: it remembers where it is and hands out the next item each time it is asked.
The test that tells an iterator from a plain container is what iter() returns:
numbers = [10, 20, 30]
z = zip([1], [2])
e = enumerate(numbers)
print(iter(numbers) is numbers) # False: a list makes a fresh iterator each time
print(iter(z) is z) # True: a zip object is its own iterator
print(iter(e) is e) # True: so is an enumerate objectA list is an iterable that can be looped over as many times as you like, because every for loop asks it for a new iterator. A zip or enumerate object is its own iterator, so asking it for "a new one" returns the same object, with the same position. Everything in this chapter follows from that fact.
The basic pitfall: a second pass finds nothing
Here is the example from the plan:
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 and raises no error. When list() (or a for loop) calls next() on the iterator, the iterator signals the end by raising StopIteration. That is the normal "no more items" signal, and for and list() catch it. Once an iterator has raised it, later calls to next() raise it again. The iterator does not reset.
The same thing happens with enumerate:
indexed = enumerate(["a", "b"])
print(next(indexed)) # (0, 'a')
print(list(indexed)) # [(1, 'b')]
print(list(indexed)) # []The first next() call took one item. list() then took the remainder, and the last call found nothing.
Silent failure is the real danger
Reusing an exhausted iterator rarely crashes. A loop over an exhausted iterator runs zero times, and the code after it carries on. A bug of this kind often shows up as a missing row in a report or a total that is too small, far from where it was introduced.
Pitfall 1: iterating twice
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
results = zip(names, scores)
for name, score in results:
print(f"{name}: {score}")
best = max(results, key=lambda pair: pair[1])The for loop uses up results. The max() call then receives an empty iterator and raises ValueError: max() iterable argument is empty. If you passed default=None to max(), you would get None and no error at all.
The fix is to turn the result into a list once, then reuse the list:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
results = list(zip(names, scores))
for name, score in results:
print(f"{name}: {score}")
best = max(results, key=lambda pair: pair[1])
print(best) # ('Ada', 95)Pitfall 2: an inner loop that only works once
This is the most common version of the bug. An iterator created outside a loop is consumed on the first outer pass:
rows = ["r1", "r2"]
cols = ["c1", "c2"]
labels = enumerate(cols)
for row in rows:
for index, col in labels:
print(row, index, col)The output is:
r1 0 c1
r1 1 c2The row r2 never appears, because labels is empty by the time the second outer pass begins. Create the iterator inside the outer loop, so each pass gets a fresh one:
rows = ["r1", "r2"]
cols = ["c1", "c2"]
for row in rows:
for index, col in enumerate(cols):
print(row, index, col)Creating enumerate(cols) repeatedly is cheap. It stores a reference to cols and a counter, and it does not copy the data.
Pitfall 3: returning an iterator from a function
A function that returns zip(...) hands the caller a one-shot object. Callers will often treat it as a list: they loop over it, then loop again, or they call len() on it. If the function's result is meant to be reused, return a list:
def pair_up(names, scores):
return list(zip(names, scores))If you want to keep the function lazy for large inputs, say so in its documentation, and name the return type honestly (for example Iterator[tuple[str, int]]).
Things a list can do that these objects cannot
An iterator supports one operation, "give me the next item". The usual list operations are therefore missing.
empty = zip([], [])
print(bool(empty)) # True
try:
len(empty)
except TypeError as error:
print(error) # object of type 'zip' has no len()
try:
empty[0]
except TypeError as error:
print(error) # 'zip' object is not subscriptablePitfall 4: truthiness checks always pass
bool(zip([], [])) is True, because the object does not define a length and Python treats a plain object as true. This code never reaches the else branch:
pairs = zip([], [])
if pairs:
print("has data")
else:
print("no data") # never printedTo check for emptiness, build the list first and test that:
pairs = list(zip([], []))
if pairs:
print("has data")
else:
print("no data")If you need to avoid building the whole list, next(pairs, None) returns the first item or None. This consumes that item, so you must keep it and use it.
Pitfall 5: len, indexing, and slicing
You cannot write len(pairs), pairs[0], or pairs[1:3]. Convert to a list first. To take a slice lazily, use itertools.islice:
from itertools import islice
indexed = enumerate(["a", "b", "c", "d"])
print(list(islice(indexed, 2))) # [(0, 'a'), (1, 'b')]
print(list(indexed)) # [(2, 'c'), (3, 'd')]Notice that islice also consumes from the underlying iterator. The first two items are gone from indexed afterward.
Partial consumption: the hidden ways to use up items
An iterator does not have to reach its end to lose items. Any operation that pulls from it moves it forward. The table lists the common ones.
| Operation | How much it consumes |
|---|---|
| `for ... in it:` with no `break` | Everything |
| `list(it)`, `tuple(it)`, `sorted(it)` | Everything |
| `sum(it)`, `max(it)`, `min(it)` | Everything |
| `any(it)`, `all(it)` | Up to the first deciding item |
| `x in it` | Up to and including the first match, or everything if none |
| `next(it)` | One item |
| `for ... in it:` ending in `break` | Up to and including the item where the loop broke |
| `len(it)`, `it[0]` | Not supported, so a `TypeError` |
Pitfall 6: a membership test eats items
indexed = enumerate(["a", "b", "c"])
print((1, "b") in indexed) # True
print(list(indexed)) # [(2, 'c')]The in test walked through (0, 'a') and (1, 'b'), then stopped. A later loop sees only what is left.
Using partial consumption on purpose
Sometimes the forward-only behavior is what you want. A loop that breaks leaves the iterator positioned just after the break, so a second loop can resume from there:
lines = enumerate(["header", "---", "row one", "row two"], start=1)
for number, text in lines:
if text == "---":
break
for number, text in lines:
print(number, text)The output is:
3 row one
4 row twoThe first loop skips the header, and the second handles the body with the line numbers intact. This is a legitimate pattern, but write a comment when you rely on it. A reader who does not expect it will see two loops over one variable and assume a bug.
Pitfall 7: zip can drop an item from an input iterator
The previous pitfalls involve the zip object itself. A subtler one involves the inputs, when those are iterators too. zip asks its inputs for items in order, left to right. When the shorter input runs out, zip has already pulled an item from each input before it.
long_input = iter([1, 2, 3, 4])
short_input = iter(["x", "y"])
print(list(zip(long_input, short_input)))
# [(1, 'x'), (2, 'y')]
print(list(long_input))
# [4]The value 3 is lost. zip took 3 from long_input, then asked short_input for a partner, found it exhausted, and stopped. The 3 was never emitted, and long_input no longer holds it.
Swapping the argument order changes the result:
long_input = iter([1, 2, 3, 4])
short_input = iter(["x", "y"])
print(list(zip(short_input, long_input)))
# [('x', 1), ('y', 2)]
print(list(long_input))
# [3, 4]Now short_input is asked first and runs out before zip touches long_input for a third item, so nothing is lost.
This only matters when you keep using an input iterator after the zip. With lists, nothing is lost, because the lists are still intact. If you do need to continue with the leftovers of an iterator, put the one you will keep using last in the argument list, or use strict=True so a length mismatch raises ValueError instead of passing silently.
Pitfall 8: the same iterator passed twice
If both arguments to zip are the same iterator, each pair takes two consecutive items:
it = iter([1, 2, 3, 4, 5, 6])
print(list(zip(it, it)))
# [(1, 2), (3, 4), (5, 6)]This works because zip pulls from the same object twice per round. It is a known idiom for grouping items in pairs, but it is easy to trigger by accident. Compare:
data = [1, 2, 3, 4, 5, 6]
print(list(zip(data, data)))
# [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]With a list, each argument gets its own iterator, and the result is what you would expect. Code that works on a list can therefore change behavior when someone passes in an iterator, such as a generator, a file object, or another zip. Files are one-shot in the same way: enumerate(open("data.txt")) can be looped over once.
Choosing a fix
There are three ways to deal with a one-shot iterator that you need more than once.
- Create it again. Call
enumerate(...)orzip(...)at the point of use. This is cheap and correct when the underlying inputs are lists, tuples, strings, or other re-iterable containers. - Materialize it. Call
list(...)ortuple(...)once. This costs memory proportional to the number of items, and it gives youlen(), indexing, and unlimited passes. - Split it with
itertools.tee. This returns independent iterators that each see every item.
from itertools import tee
pairs = zip([1, 2, 3], ["a", "b", "c"])
first, second = tee(pairs)
print(list(first)) # [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(second)) # [(1, 'a'), (2, 'b'), (3, 'c')]After calling tee, do not use the original pairs again, because it shares state with the copies. tee also buffers every item that one copy has read and the others have not. If you finish first before starting second, the buffer holds everything, which is the same memory cost as list() with more complexity. Use tee when the copies advance roughly together, such as in a streaming computation over data that is too large for memory.
Creating the iterator again is the default choice. It is only wrong when the input is itself a one-shot iterator, such as a generator or a file, because a second zip over an exhausted input is empty too.
A short debugging checklist
When a loop over a zip or enumerate result seems to skip or lose data, work through these questions in order:
- Is the object stored in a variable and used in more than one place?
- Did any earlier
in,next(),break,sum(), orlist()touch it? - Is it created outside an outer loop but used inside?
- Are any of the inputs themselves iterators, and are they used again after the
zip? - Does an
if pairs:check exist that cannot ever be false?
A quick test is to print type(obj). If the output is <class 'zip'> or <class 'enumerate'>, you have a one-shot object, and it should be consumed in exactly one place.
Summary of the rules
zipandenumeratereturn iterators that move forward only and cannot be reset.- A second
fororlist()over the same object yields nothing and raises no error. - Iterators have no
len(), indexing, or meaningful truthiness. Convert to a list when you need those. in,next(),break,any(), andall()consume part of an iterator.- With iterator inputs,
zipcan silently discard one item from an input that is checked before the shortest one runs out. - Fix reuse by creating the iterator again, materializing it with
list(), or splitting it withtee.
Exercise
The code below prints a header and then should print each pair, but it prints "Total: 0" and the loop prints nothing. Explain why, and fix it so both outputs are correct. names = ["Ada", "Grace"] scores = [95, 88] pairs = zip(names, scores) total = sum(score for _, score in pairs) for name, score in pairs: print(name, score) print("Total:", total)
Show answer
The code first computes the total with a generator over pairs. This runs the zip object to the end, so it is exhausted when the for loop starts. The loop therefore runs zero times. Note that the total is actually 183, so the stated "Total: 0" does not match this code; the visible bug is that the loop prints nothing. The fix is to materialize the pairs once with pairs = list(zip(names, scores)), after which both the sum and the loop see all items. Alternatively, create zip(names, scores) separately for each use.
Exercise
What do the two print calls output, and why is the number 3 missing from the second one? source = iter([1, 2, 3, 4]) letters = iter(["a", "b"]) print(list(zip(source, letters))) print(list(source))
Show answer
The first call prints [(1, 'a'), (2, 'b')]. The second prints [4]. During the third round zip pulled 3 from source, then asked letters for a partner and found it exhausted, so it stopped without emitting 3. The value 3 had already been removed from source, so it is lost. Writing zip(letters, source) would leave 3 in source, because letters would be asked first and would run out before source was touched.
Exercise
A colleague writes if zip(a, b): to check that two lists have matching data. Why does this not work, and what is a correct way to test whether the pairing is non-empty?
Show answer
A zip object defines no length and is always truthy, so the condition is true even when both lists are empty. A correct check is to build a list and test it: pairs = list(zip(a, b)) followed by if pairs:. Another way is first = next(zip(a, b), None) followed by if first is not None:, which avoids building the whole list but needs a fresh zip for the later loop, since the item was consumed.