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. You should be comfortable with generators, comprehensions, and the key= argument of sorted. The tools in itertools are fast and use little memory. Most bugs with them come from three properties: iterators are consumed once, work happens lazily, and some functions share state behind the scenes. Learn these failure modes and you can also tell when plain Python is the better choice.
Pitfall 1: Exhausted iterators
An iterator gives each item once. After a full pass it is empty, and no error is raised.
it = map(str, range(3))
print(list(it))
print(list(it))The first call prints ['0', '1', '2']. The second prints [].
The bug is more dangerous inside a function that loops over its argument twice. It works with lists and fails silently with generators.
def share(values):
total = sum(values)
return [v / total for v in values]
print(share([1, 2, 3]))
print(share(v for v in [1, 2, 3]))The list gives [0.16666666666666666, 0.3333333333333333, 0.5]. The generator gives [], because sum used up every item before the comprehension started.
You have two fixes:
- Convert once at the top with
values = list(values). This costs memory but is correct for any iterable. - Document that the function needs a re-iterable sequence, and check it with
isinstance(values, collections.abc.Sequence)if you want to fail early.
Pitfall 2: Functions that consume more than you expect
Some tools read one item past the data they return. takewhile must read the first failing item to know it should stop, and that item is lost.
from itertools import takewhile
it = iter([1, 4, 6, 2, 3])
print(list(takewhile(lambda x: x < 5, it)))
print(list(it))The output is [1, 4] and then [2, 3]. The value 6 was consumed and thrown away. If you need that boundary item, use a list and an index, or write a small loop that keeps it.
islice has a related cost. It cannot jump, so islice(data, 1_000_000, 1_000_003) walks through a million items to reach the start. For a list or tuple, ordinary slicing data[1_000_000:1_000_003] is much cheaper. islice also rejects negative start, stop, or step values, because an iterator has no known end.
Pitfall 3: groupby on unsorted data
groupby groups only consecutive items with equal keys. It does not gather matching items from across the whole input.
from itertools import groupby
words = ['apple', 'avocado', 'banana', 'apricot']
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, list(group))This prints three groups: a ['apple', 'avocado'], b ['banana'], and then a second a ['apricot']. Sort by the same key first. That costs O(n log n) time and needs the data in memory.
The second trap is that each group is a view on the shared source iterator. When groupby moves to the next key, the previous group becomes invalid.
from itertools import groupby
print([(k, list(g)) for k, g in groupby("aabbb")])
bad = list(groupby("aabbb"))
print([(k, list(g)) for k, g in bad])The first line prints [('a', ['a', 'a']), ('b', ['b', 'b', 'b'])]. The second prints [('a', []), ('b', [])], because list(groupby(...)) advanced past every group before you read any of them. Always consume each group inside the loop or comprehension, as in the first line.
Pitfall 4: tee buffers and the original iterator
tee returns independent iterators, but they share a buffer. Items are stored until every copy has read them. If one copy runs far ahead, the buffer holds everything in between.
from itertools import tee
source = iter([1, 2, 3])
a, b = tee(source)
print(next(source))
print(list(a))
print(list(b))The output is 1, [2, 3], and [2, 3]. Advancing source directly stole an item from both copies. After calling tee, use only the copies.
If you read one copy completely before touching the other, tee stores the whole stream, which is no better than list(...). In that case use list, because it is clearer and lets you iterate any number of times. Reserve tee for copies that advance roughly in step.
Pitfall 5: Lazy evaluation and late binding
Lazy objects run later, so they see variables as they are when they finally run, not as they were when you built them.
evens_and_threes = [
filter(lambda x: x % n == 0, range(10)) for n in (2, 3)
]
print(list(evens_and_threes[0]))You might expect [0, 2, 4, 6, 8]. The output is [0, 3, 6, 9]. The lambda looks up n when list(...) runs, and by then n is 3 for both filters. Bind the value at creation time:
evens_and_threes = [
filter(lambda x, n=n: x % n == 0, range(10)) for n in (2, 3)
]
print(list(evens_and_threes[0]))
print(list(evens_and_threes[1]))Now the output is [0, 2, 4, 6, 8] and [0, 3, 6, 9].
Lazy code also delays errors and side effects. A ValueError in a mapped function appears at the point of consumption, possibly far from the line that built the pipeline. Printing or writing inside a lazy stage does nothing until something consumes it. If a stage never runs, check that the pipeline ends in a loop, list, sum, or deque(it, maxlen=0).
Pitfall 6: Infinite and exploding inputs
Infinite iterators (count, cycle, repeat without a count) must be bounded before anything that reads everything. list(count()), sorted(cycle(...)), and product(count(), ...) never finish and use ever more memory. product, permutations, and combinations first read their inputs into tuples, so they need finite inputs. cycle also keeps a copy of the first pass.
The combinatoric tools have a different risk, which is size. The output is lazy, but the count grows quickly. Check it before you loop:
from math import comb, perm
print(perm(10, 10))
print(comb(50, 5))
print(2 ** 20)This prints 3628800, 2118760, and 1048576. The last number is how many tuples product('01', repeat=20) would produce. Iterating a few thousand results is fine. Iterating billions is not, whatever the memory use.
Pitfall 7: Version differences
pairwise needs Python 3.10 or later, and batched needs 3.12 or later. On older versions, importing them raises ImportError.
When not to use itertools
Lazy tools suit large or unbounded streams and one-pass processing. They are the wrong choice in several situations.
| Situation | Better choice | Why |
|---|---|---|
| Small data, simple transform | List or generator comprehension | Easier to read, and the reader sees the result shape. |
| Need `len`, indexing, or several passes | `list` or `tuple` | Iterators support none of these. |
| Slicing a list or tuple | `data[a:b]` | Direct slicing does not walk the skipped items. |
| Totals, minimums, or "any match" | `sum`, `max`, `any`, `all` | Built-ins state the intent directly. |
| Large numeric arrays | NumPy or pandas | Vectorised code is far faster than Python-level iteration. |
| Complex stateful logic | A generator function with `yield` | Named variables and comments beat five nested calls. |
A pipeline can be too clever. Compare these two versions of "sum the squares of positive numbers":
from itertools import filterfalse
values = [3, -1, 4, -1, 5]
total_a = sum(map(pow, filterfalse(lambda x: x <= 0, values), [2] * 3))
total_b = sum(x * x for x in values if x > 0)
print(total_a, total_b)Both print 50. The first version works only because map stops at the shortest input, so the hard-coded [2] * 3 happens to match the three positive values. Adding data would silently drop items from the sum. The second version has no such coupling. Use itertools where it removes real work, such as chain.from_iterable for flattening, islice for bounding, and groupby for runs. Do not use it only to avoid writing a loop.
A practical checklist before you commit a pipeline:
- Does anything iterate the same iterator twice?
- Is every infinite source bounded before a consuming step?
- Is
groupbyinput sorted by the same key, and is every group consumed immediately? - Does any lambda depend on a loop variable that will change?
- Would a comprehension or a short generator function be easier to read?
Exercise
A function normalize(values) runs lo, hi = min(values), max(values) and then returns [(v - lo) / (hi - lo) for v in values]. It works for lists but returns [] for a generator argument. Why, and what is the smallest fix?
Show answer
min and max each consume the generator, so nothing is left for the comprehension, and the final loop sees an exhausted iterator. (The call to max would also already see an empty iterator, and raises ValueError, so a generator input can fail even earlier than the comprehension.) The smallest fix is to add values = list(values) as the first line, so the data is stored once and can be iterated repeatedly.
Exercise
What does this code print, and why? from itertools import groupby pairs = [(1, 'a'), (2, 'b'), (1, 'c')] print([(k, [v for _, v in g]) for k, g in groupby(pairs, key=lambda p: p[0])]) How do you get one group per key?
Show answer
It prints [(1, ['a']), (2, ['b']), (1, ['c'])]. groupby only joins neighbouring items, so key 1 appears twice. Sort first with pairs.sort(key=lambda p: p[0]) (or sorted(...)) using the same key function. The result is then [(1, ['a', 'c']), (2, ['b'])], because sort is stable and keeps a before c.
Exercise
You have a 5-million-line log file and need two passes over each line: one to count errors, one to collect timestamps. Is tee a good fit?
Show answer
Only if both consumers advance together, line by line, in a single loop. If you finish the first pass before starting the second, tee buffers all 5 million lines in memory, as list would. A better design is usually one loop that updates both results, or reopening the file for the second pass, since a file can be read again.