Sub topic 14
Common pitfalls and when not to use itertools
This chapter assumes you have read the earlier chapters on iterators, groupby, tee and pipelines. It collects the mistakes that cause most itertools bugs and gives rules for choosing a plain list or loop instead.
Pitfall 1: Reusing an exhausted iterator
An iterator can be read once. After a full pass, it yields nothing, and Python raises no error.
nums = map(int, "123")
total = sum(nums)
leftover = list(nums)
print(total, leftover)This prints 6 []. If you need several passes, store the data with list(...) or rebuild the iterator each time. Pass an iterable that can be re-read, such as a list, to any function that loops twice.
Pitfall 2: Unsorted input to groupby
groupby starts a new group each time the key changes. It does not gather equal keys from across the whole input. Sort by the same key first, or accept that repeated keys produce separate groups.
A second trap is that each group is a view on the shared source. Advancing to the next group invalidates the previous one. Consume each group inside the loop, or copy it with list(g):
from itertools import groupby
print([(k, list(g)) for k, g in groupby("aabbb")])This prints [('a', ['a', 'a']), ('b', ['b', 'b', 'b'])]. Because list(g) runs before the outer loop advances, each group is complete.
Pitfall 3: Unbounded tee buffers and infinite streams
tee stores every item that one copy has read and another has not. If one copy runs far ahead, memory grows with the gap. In the worst case you hold the whole stream, which removes the benefit of lazy iteration. Do not use the original iterator after calling tee on it. If the data fits in memory, list(...) is simpler and faster.
Infinite iterators have a similar risk. list(count()) and sum(cycle("ab")) never finish. Bound them with islice or takewhile, or stop a loop with break.
Pitfall 4: Combinatorial explosion
product, permutations and combinations are lazy, but the number of results can still be huge. Check the size before you loop:
from math import comb, perm
print(comb(50, 5))
print(perm(10, 10))This prints 2118760 and 3628800. Looping over millions of tuples is slow even though memory use is small.
Pitfall 5: Version differences
pairwise needs Python 3.10 or later, and batched needs 3.12 or later. On older versions you get an ImportError. Check your minimum supported Python version before you use them.
When not to use itertools
Choose the simpler tool when the data is small or when you need features that iterators lack.
| Situation | Better choice |
|---|---|
| You need `len()`, indexing or negative slices | A list or tuple |
| You need several passes over the data | A list |
| A comprehension says the same thing in one line | A comprehension |
| Counting or grouping by key across unsorted data | `collections.Counter` or `defaultdict` |
| The chain of calls is hard to read | A named generator function |
Best practices
- Name each stage of a long pipeline, or move it into a generator function with a docstring.
- Bound every infinite iterator at the point where you create it.
- Sort before
groupby, and consume groups immediately. - Prefer
listoverteewhen the data is small. - Estimate result counts before using combinatoric iterators.
Exercise
A script does rows = csv.reader(f), then header_count = sum(1 for _ in rows), then for row in rows: process(row). The loop never runs. Why, and what are two ways to fix it?
Show answer
The first line of code reads rows to the end, so the iterator is exhausted when the for loop starts. Fix it by storing the rows once with rows = list(csv.reader(f)), or by counting with a separate pass: call f.seek(0) and create a new reader before the loop.
Exercise
You call groupby on ["b", "a", "b"] with the identity key and no sorting. How many groups do you get, and what single change gives you two groups?
Show answer
You get three groups: b, a and b. Calling sorted(...) on the list first gives ["a", "b", "b"], which produces two groups.