Sub topic 8
Pairing items with zip_longest and pairwise
This chapter assumes you know Python loops, tuples and the built-in zip. It also assumes you know that an iterator can be consumed only once. Two itertools tools extend what zip can do. zip_longest handles inputs of unequal length. pairwise looks at neighbouring items in a single stream.
What the built-in zip does with uneven inputs
The built-in zip stops as soon as its shortest input runs out. Items from longer inputs are dropped without any warning.
names = ['a', 'b', 'c']
nums = [1, 2]
print(list(zip(names, nums)))This prints [('a', 1), ('b', 2)]. The 'c' is lost. Sometimes that is what you want. When it is not, you need a tool that keeps going.
Padding with zip_longest
zip_longest runs until the longest input is exhausted. Missing values are filled with fillvalue, which defaults to None.
from itertools import zip_longest
print(list(zip_longest('ab', [1, 2, 3], fillvalue='-')))The output is [('a', 1), ('b', 2), ('-', 3)]. The shorter input, 'ab', is padded with '-'.
The function accepts any number of iterables, and they can be iterators. It reads them lazily, one item from each per step, so it is safe to use on large streams.
A practical use: summing columns of ragged rows
from itertools import zip_longest
rows = [[1, 2, 3], [4, 5], [6]]
totals = [sum(col) for col in zip_longest(*rows, fillvalue=0)]
print(totals)This prints [11, 7, 3]. Transposing with plain zip(*rows) would give only [(1, 4, 6)], which has one column instead of three. Choose a fillvalue that is neutral for your operation. Here 0 does not change a sum.
If unequal lengths are a bug in your data, use zip(a, b, strict=True) (Python 3.10+). It raises ValueError instead of silently truncating or padding.
Neighbouring items with pairwise
pairwise (Python 3.10+) yields overlapping pairs of consecutive items from one iterable. For input x0, x1, x2, ... it yields (x0, x1), (x1, x2), and so on.
from itertools import pairwise
print(list(pairwise([1, 4, 9, 16])))The output is [(1, 4), (4, 9), (9, 16)]. An input with fewer than two items produces no pairs.
Differences between neighbours
Pairs make it easy to compare each item with the one before it.
from itertools import pairwise
temps = [18, 21, 20, 25]
changes = [b - a for a, b in pairwise(temps)]
print(changes)This prints [3, -1, 5]. You can also check whether data is sorted with all(a <= b for a, b in pairwise(data)).
Because pairwise works on any iterable, it also works on a generator whose items you cannot index. Before Python 3.10 you had to write this yourself with tee and next. On older versions, that recipe is the standard workaround.
Choosing between the tools
| Need | Tool | Result length for inputs of length m and n |
|---|---|---|
| Stop at the shortest input | `zip` | min(m, n) |
| Keep everything, pad gaps | `zip_longest` | max(m, n) |
| Fail on unequal lengths | `zip(strict=True)` | m, or `ValueError` |
| Overlapping neighbours | `pairwise` | m - 1 (or 0) |
Common errors
- Forgetting that
zip_longestyieldsNonefor missing values, then calling arithmetic on it. This raisesTypeError. - Passing an infinite iterator to
zip_longest. It will never stop, because the infinite input is never exhausted. Bound it withislicefirst. - Expecting
pairwiseto give non-overlapping pairs. For that, you need batches of two, which a later chapter covers. - Reusing an iterator after
pairwisehas consumed it. The same single-pass rule applies as everywhere else.
Exercise
Given a = [1, 2, 3] and b = [10, 20], write one expression that returns the list of sums of corresponding items, treating missing values as 0. What does it return?
Show answer
[x + y for x, y in zip_longest(a, b, fillvalue=0)] returns [11, 22, 3]. The missing fourth-position value in b is replaced by 0, so the last sum is 3 + 0.
Exercise
What does list(pairwise('abcd')) return, and how many pairs would pairwise yield for an input of 10 items?
Show answer
It returns [('a', 'b'), ('b', 'c'), ('c', 'd')]. For 10 items it yields 9 pairs, because the number of pairs is one less than the number of items.