Sub topic 11
Useful tools from itertools
This chapter assumes you know the iterator protocol, can write generator functions and generator expressions, and understand that generators are lazy and single-use. The itertools module is a standard-library collection of functions that build and combine iterators. Each function takes iterables and returns an iterator, so the results are lazy and fit directly into the generator pipelines from the previous chapter.
Why itertools exists
You could write each of these tools yourself as a generator. The itertools versions are implemented in C, tested, and named so that other readers recognise them. They also handle edge cases you might miss, such as an empty input or a step of zero.
The functions fall into three groups.
Infinite sources: count, cycle, repeat
These three never stop on their own, so always pair them with a limit such as islice, zip, or takewhile.
count(start=0, step=1)yields numbers forever.cycle(iterable)repeats the items of a finite iterable forever. It saves a copy of each item the first time through.repeat(value, times)yields the same value. Withouttimesit never stops.
from itertools import count, cycle, islice, repeat
print(list(islice(count(10, 5), 3))) # [10, 15, 20]
print(list(islice(cycle("ab"), 5))) # ['a', 'b', 'a', 'b', 'a']
print(list(repeat("x", 3))) # ['x', 'x', 'x']A common use of repeat is as a constant argument to map. map(pow, [1, 2, 3], repeat(2)) squares each number.
Slicing a stream with islice
You cannot slice an iterator with it[2:5], because iterators do not support indexing. islice(iterable, start, stop, step) gives you the same result lazily. The signature follows range, and it accepts only non-negative values.
from itertools import islice
print(list(islice("abcdefgh", 2, 7, 2))) # ['c', 'e', 'g']
print(list(islice("abcdefgh", 3))) # ['a', 'b', 'c']islice has to consume and discard the items before start. It cannot jump ahead, because an iterator has no random access. It also advances the underlying iterator, which matters when you reuse it:
from itertools import islice
it = iter(range(10))
print(list(islice(it, 3))) # [0, 1, 2]
print(list(islice(it, 3))) # [3, 4, 5]
print(next(it)) # 6Each call continues where the last one stopped. Taking the first N items of a stream and then the next N is a handy way to read data in steps.
Combining iterables: chain and zip_longest
chain(*iterables) treats several iterables as one long sequence, without building a combined list.
from itertools import chain
print(list(chain([1, 2], (3,), "ab"))) # [1, 2, 3, 'a', 'b']
nested = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(nested))) # [1, 2, 3, 4, 5]chain.from_iterable takes one iterable of iterables. It is the standard way to flatten one level of nesting. It is also lazy about the outer iterable, so the outer iterable can itself be a generator.
The built-in zip stops at the shortest input. zip_longest runs to the longest input and fills the gaps.
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], "ab", fillvalue="-")))
# [(1, 'a'), (2, 'b'), (3, '-')]Without fillvalue, the gaps are None. That default can hide bugs if None is also a valid data value, so pass a fill value explicitly.
Stopping and skipping by condition
takewhile(predicate, iterable) yields items until the predicate first returns false, then stops for good. dropwhile does the opposite. It discards items while the predicate is true, then yields everything that remains.
from itertools import dropwhile, takewhile
data = [1, 3, 5, 2, 7]
print(list(takewhile(lambda x: x < 4, data))) # [1, 3]
print(list(dropwhile(lambda x: x < 4, data))) # [5, 2, 7]Both look only at the first transition. takewhile does not resume when 2 and 7 come later, and dropwhile does not drop them again. Use the built-in filter when you want to test every item.
takewhile is useful on infinite streams, where it acts as a stopping condition:
from itertools import count, takewhile
squares_under_50 = takewhile(lambda n: n < 50, (x * x for x in count(1)))
print(list(squares_under_50)) # [1, 4, 9, 16, 25, 36, 49]Running totals with accumulate
accumulate(iterable, func) yields the running result of applying a two-argument function. With no function it adds.
from itertools import accumulate
print(list(accumulate([1, 2, 3, 4]))) # [1, 3, 6, 10]
print(list(accumulate([3, 1, 4, 1, 5], max))) # [3, 3, 4, 4, 5]
print(list(accumulate([1, 2, 3], initial=100))) # [100, 101, 103, 106]The initial keyword (Python 3.8 and later) puts a starting value in front of the output. Note that the output then has one more item than the input.
Grouping with groupby
groupby(iterable, key) groups consecutive items that share the same key. It yields pairs of (key, group), where group is itself an iterator.
from itertools import groupby
words = sorted(["apple", "banana", "avocado", "blueberry", "cherry"])
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, list(group))
# a ['apple', 'avocado']
# b ['banana', 'blueberry']
# c ['cherry']Two behaviours catch people out.
- It groups only neighbours. Unlike SQL
GROUP BY,groupbydoes not sort. If equal keys are not adjacent, you get several groups for the same key. Sort by the same key first, as the example does. - Groups share the source iterator. Each
groupis valid only until you move to the next key. If you need the items later, copy them withlist(group)before advancing.
from itertools import groupby
print([(k, len(list(g))) for k, g in groupby("aabaa")])
# [('a', 2), ('b', 1), ('a', 2)]The two separate 'a' groups show the neighbours-only rule. Sorting the input first would merge them into a single ('a', 4) group.
Splitting one iterator with tee
tee(iterable, n=2) returns n independent iterators over the same input. This lets two consumers read the same single-use stream.
from itertools import tee
first, second = tee(iter([1, 2, 3]))
print(list(first)) # [1, 2, 3]
print(list(second)) # [1, 2, 3]Internally, tee buffers every item that one copy has read and another has not. If one copy runs far ahead, the buffer grows, which defeats the memory savings of lazy evaluation. When the data is small, list(iterable) is simpler and often cheaper. Once you call tee, stop using the original iterator. Advancing it directly makes the copies miss items.
Windows and chunks: pairwise and batched
Two newer helpers replace patterns people used to write by hand. pairwise needs Python 3.10 or later. batched needs Python 3.12 or later.
from itertools import batched, pairwise
print(list(pairwise([1, 4, 9, 16]))) # [(1, 4), (4, 9), (9, 16)]
print(list(batched("abcdefg", 3))) # [('a', 'b', 'c'), ('d', 'e', 'f'), ('g',)]pairwise is ideal for differences between neighbouring values. batched is ideal for sending records to a database or API in chunks. The last batch can be shorter than the others.
from itertools import pairwise
temps = [18, 21, 20, 25]
print([b - a for a, b in pairwise(temps)]) # [3, -1, 5]Combinatorics at a glance
product, permutations, and combinations produce tuples that you would otherwise build with nested loops.
| Function | What it yields | Example result for `"abc"`, size 2 |
|---|---|---|
| `product(a, b)` | Every pairing, like nested loops | not applicable to a single input |
| `permutations(x, r)` | Ordered selections without repeats | `ab ac ba bc ca cb` |
| `combinations(x, r)` | Unordered selections without repeats | `ab ac bc` |
from itertools import combinations, product
print(list(combinations("abc", 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]
print(list(product([0, 1], repeat=2)))
# [(0, 0), (0, 1), (1, 0), (1, 1)]These grow fast. Ten items taken three at a time with permutations give 720 results, and twenty items give 6,840. The iterators are lazy, so you can stop early, but do not wrap them in list() without checking the size.
Putting tools together
Because every tool returns an iterator, they chain like the generator stages you wrote earlier. This example takes the first five even squares greater than 10 from an endless stream.
from itertools import count, dropwhile, islice
evens = (n for n in count(1) if n % 2 == 0)
squares = (n * n for n in evens)
result = islice(dropwhile(lambda s: s <= 10, squares), 5)
print(list(result)) # [16, 36, 64, 100, 144]Nothing runs until list pulls values. The infinite count is safe because islice stops the pull after five items.
Common errors
- Calling
list()on an infinite iterator. This runs until memory is exhausted. Putisliceortakewhilein front. - Forgetting to sort before
groupby. The result is split groups, with no error. - Reading a
groupbygroup late. The group is empty or wrong once you advance. Convert it to a list first. - Reusing the source after
tee. Use only the returned copies. - Expecting reusable results. Every function here returns a single-use iterator. A second
list()on the same object gives an empty list.
Exercise
Given words = ["bat", "bar", "cat", "cow", "ant"], use groupby to build a dictionary mapping each first letter to the list of words that start with it. Explain why the input must be sorted first, and say what the result is.
Show answer
from itertools import groupby words = ["bat", "bar", "cat", "cow", "ant"] ordered = sorted(words) result = {k: list(g) for k, g in groupby(ordered, key=lambda w: w[0])} print(result) # {'a': ['ant'], 'b': ['bar', 'bat'], 'c': ['cat', 'cow']} groupby only joins neighbouring items with equal keys, so sorting by the same key puts all words with one first letter next to each other. Without sorting, repeated letters would create repeated groups, and a dictionary built from them would overwrite earlier groups with later ones. The list(g) call copies each group before the iteration moves on.
Exercise
Write a generator-free expression using itertools that yields the running maximum of the stream [2, 7, 3, 9, 4], and say what it prints. Then add a line that returns only the first three values.
Show answer
from itertools import accumulate, islice stream = [2, 7, 3, 9, 4] runningmax = accumulate(stream, max) print(list(runningmax)) # [2, 7, 7, 9, 9] runningmax = accumulate(stream, max) print(list(islice(runningmax, 3))) # [2, 7, 7] The accumulate iterator is single-use, so the second example creates a new one. Calling list on the old iterator would give an empty list.