Python's itertools: Lazy, Composable Iterators
An examination of the itertools module by family, from infinite iterators and chaining to grouping and combinatorics, with measurements of the memory it saves and the pitfalls of lazy iteration.
Many loops in Python repeat the same few shapes: walking through several collections one after another, taking the first elements of a long stream, grouping consecutive records or generating every pair of a set. The module itertools of the standard library provides each of these shapes as a ready-made iterator, implemented in C and composable with the others. The present article examines its main tools by family, measures the memory they save and identifies the pitfalls that follow from their lazy nature. The ability to combine small iterators into a pipeline that never builds an intermediate list is the secret weapon of this module.
Lazy Iterators
Every function of itertools returns an iterator, an object that produces one element each time it is asked for the next one and stores nothing else. This is the same principle that governs generators, examined in the article devoted to yield, and its practical consequence is easy to measure with tracemalloc.
import itertools
import tracemalloc
first = list(range(1_000_000))
second = list(range(1_000_000))
tracemalloc.start()
total = sum(first + second)
print(f"concatenation peak: {tracemalloc.get_traced_memory()[1] / 1e6:.1f} MB")
tracemalloc.stop()
tracemalloc.start()
total = sum(itertools.chain(first, second))
print(f"chain peak: {tracemalloc.get_traced_memory()[1] / 1e6:.4f} MB")
tracemalloc.stop()
# Output (CPython 3.12, 64-bit): concatenation peak: 16.0 MB
# Output (CPython 3.12, 64-bit): chain peak: 0.0001 MB
The expression first + second builds a third list of two million references only to traverse it once, whereas chain walks through the first list and then through the second without copying either. Laziness saves memory and start-up time, although it does not make every operation faster: when the same data must be traversed several times, a list remains the appropriate structure.
Infinite Iterators and How to Stop Them
Three functions produce endless sequences: count generates consecutive numbers, cycle repeats the elements of an iterable and repeat returns the same object again and again. An infinite iterator is useful only together with something that stops it, such as zip with a finite iterable or islice, which takes a slice of any iterator without indexing it.
from itertools import count, cycle, islice, repeat
print(list(islice(count(10, 5), 4))) # Output: [10, 15, 20, 25]
rows = ["alpha", "beta", "gamma", "delta", "epsilon"]
for row, shade in zip(rows, cycle(["white", "grey"])):
print(row, shade)
# Output: alpha white, beta grey, gamma white, delta grey, epsilon white
print(list(map(pow, range(5), repeat(2)))) # Output: [0, 1, 4, 9, 16]
The second example alternates two shades over the rows of a report, and zip stops as soon as the finite list ends. The third passes a constant argument to map, which is the typical use of repeat. Without islice or zip, any of these loops would never terminate.
Combining, Slicing and Pairing
A second family reorganizes finite iterables. Besides chain, which concatenates its arguments, chain.from_iterable flattens an iterable of iterables, zip_longest pairs sequences of different lengths with a fill value, pairwise (Python 3.10) returns overlapping pairs of consecutive elements, and batched (Python 3.12) splits a stream into tuples of a fixed size.
from itertools import batched, chain, pairwise, zip_longest
nested = [[1, 2], [3], [4, 5, 6]]
print(list(chain.from_iterable(nested))) # Output: [1, 2, 3, 4, 5, 6]
print(list(zip_longest("ABC", "xy", fillvalue="-")))
# Output: [('A', 'x'), ('B', 'y'), ('C', '-')]
readings = [1, 4, 9, 16]
print([b - a for a, b in pairwise(readings)]) # Output: [3, 5, 7]
print(list(batched("ABCDEFG", 3)))
# Output: [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
The differences computed with pairwise replace the error-prone pattern of indexing readings[i] and readings[i + 1], and batched is the natural tool for sending records to an API in groups of fixed size. Since Python 3.13, batched accepts strict=True, which raises ValueError when the last batch is incomplete.
Grouping and Accumulating
The function groupby collects consecutive elements that share a key, and accumulate returns running totals or, with a function, any running result. The key of groupby is a function supplied by the caller, the same kind of interchangeable behaviour described in the article devoted to the Strategy pattern.
from itertools import accumulate, groupby
from operator import itemgetter
sales = [
("north", 120), ("south", 80), ("north", 50), ("south", 70), ("east", 30),
]
by_region = sorted(sales, key=itemgetter(0))
for region, rows in groupby(by_region, key=itemgetter(0)):
print(region, sum(amount for _, amount in rows))
# Output: east 30, north 170, south 150
print(list(accumulate([3, 1, 4, 1, 5]))) # Output: [3, 4, 8, 9, 14]
print(list(accumulate([3, 1, 4, 1, 5], max))) # Output: [3, 3, 4, 4, 5]
The call to sorted is not optional. groupby only compares each element with the previous one, so it groups consecutive elements rather than equal ones, and unsorted data produces several groups with the same key, as the pitfalls section shows. The second call to accumulate replaces the sum with max and yields the highest value seen so far at every position.
Party Composition: Combinatoric Iterators
Choosing which members form a group, and in which order, is the domain of the combinatoric iterators. product returns the Cartesian product, equivalent to nested loops; permutations returns ordered arrangements; combinations returns unordered selections without repetition; and combinations_with_replacement allows an element to appear more than once.
import math
import sys
from itertools import combinations, permutations, product
members = ["Ana", "Ben", "Carla", "Dev"]
print(list(combinations(members, 2))[:3])
# Output: [('Ana', 'Ben'), ('Ana', 'Carla'), ('Ana', 'Dev')]
print(len(list(combinations(members, 2)))) # Output: 6
print(len(list(permutations(members, 2)))) # Output: 12
print(list(product("ab", repeat=2)))
# Output: [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
triples = combinations(range(100), 3)
print(sys.getsizeof(triples), math.comb(100, 3)) # Output (CPython 3.12): 96 161700
Six pairs result when order is ignored and twelve when it matters, because each pair can be arranged in two ways. The last line shows the value of laziness in this family: the iterator occupies 96 bytes while it describes 161,700 triples. The functions math.comb and math.perm compute these counts without generating anything, which is the prudent check before iterating, because the number of combinations grows very quickly with the size of the input.
Pitfalls of itertools
Laziness brings its own class of errors, which appear silently instead of raising exceptions. Five pitfalls are distinguished, which are the following:
- Single use. An iterator is exhausted after one traversal; a second loop over it produces nothing.
- Unsorted input to
groupby. Groups are formed from consecutive elements, so the input must be sorted by the same key. - Groups consumed too late. Each group of
groupbyshares the underlying iterator; advancing to the next key invalidates the previous group. - Hidden storage.
cyclekeeps a copy of every element it has seen, andteestores the elements that one of its copies has consumed and the others have not. - Infinite loops.
count,cycleandrepeatwithout a stopping condition never end.
The first three pitfalls are reproduced in the following example.
from itertools import combinations, groupby
pairs = combinations("ABCD", 2)
print(len(list(pairs)), len(list(pairs))) # Output: 6 0
words = ["apple", "banana", "apricot", "blueberry"]
first_letter = lambda word: word[0]
print([(key, list(group)) for key, group in groupby(words, key=first_letter)])
# Output: [('a', ['apple']), ('b', ['banana']), ('a', ['apricot']), ('b', ['blueberry'])]
groups = list(groupby(sorted(words), key=first_letter))
print([(key, list(group)) for key, group in groups])
# Output: [('a', []), ('b', [])]
The second traversal of pairs finds the iterator already exhausted, and the first call to groupby returns the letter a twice because the words are not sorted. The last case is the most surprising: list(groupby(...)) advances through every key before any group is read, so all the groups are empty by the time they are consumed. Converting each group with list(group) inside the loop, as the earlier examples do, avoids the problem.
Choosing the Right Tool
Consequently, most loops that combine, slice or group iterables have a direct counterpart in itertools, and the following table summarizes the correspondence.
| Need | Recommended tool |
|---|---|
| Traverse several iterables as one | chain, or chain.from_iterable for nested ones |
| First n elements of any iterator | islice |
| Alternate a fixed pattern over a sequence | zip with cycle |
| Consecutive pairs or fixed-size chunks | pairwise, batched |
| Group records that share a key | sorted followed by groupby with the same key |
| Running totals, maxima or balances | accumulate |
| Pairs, arrangements or nested loops | combinations, permutations, product |
| Data that must be traversed several times | A list, not an iterator |
Conclusion
It is concluded that itertools turns the most frequent shapes of iteration into small, lazy and composable building blocks, which save memory because they never build intermediate collections and save code because they replace index arithmetic and nested loops. This magic depends on a single rule that explains all of its pitfalls: an iterator produces each element once and keeps nothing it does not need, so data must be sorted before groupby, consumed in time and materialized when it must be read twice. The iterator protocol itself, through which a for loop obtains and advances these objects with iter() and next(), is developed in a future article of this series.