Sub topic 8
Pairing items with zip_longest and pairwise
This chapter assumes you are comfortable with the built-in zip, tuple unpacking in for loops, and the iterator protocol from the first chapter (an iterator is consumed as you read it). You should also know how itertools tools stay lazy, which the earlier chapters on lazy evaluation covered.
Two itertools tools solve problems that zip handles badly:
zip_longestpairs items from inputs of unequal length without dropping data.pairwisepairs each item with the one after it in a single stream.
What zip does with unequal inputs
The built-in zip stops when its shortest input runs out. Extra items from longer inputs are silently discarded.
names = ['Ana', 'Ben', 'Cy']
scores = [90, 85]
print(list(zip(names, scores)))This prints [('Ana', 90), ('Ben', 85)]. Cy has vanished, and no error was raised. For data you must not lose, such as records from two sources, this silent truncation is a bug waiting to happen.
Since Python 3.10, zip(..., strict=True) raises a ValueError instead of truncating. Use it when unequal lengths mean the data is broken. Use zip_longest when unequal lengths are normal and you want to keep every item.
try:
list(zip([1, 2, 3], 'ab', strict=True))
except ValueError as error:
print(error)This prints zip() argument 2 is shorter than argument 1.
zip_longest: padding the shorter inputs
zip_longest(*iterables, fillvalue=None) keeps going until the longest input is exhausted. When a shorter input runs out, it supplies fillvalue in its place.
from itertools import zip_longest
names = ['Ana', 'Ben', 'Cy']
scores = [90, 85]
print(list(zip_longest(names, scores)))
print(list(zip_longest(names, scores, fillvalue=0)))The first call prints [('Ana', 90), ('Ben', 85), ('Cy', None)]. The second prints the same list with ('Cy', 0) as the last tuple.
Properties worth knowing
- It accepts any number of inputs, not just two. Every exhausted input is padded independently.
- It is lazy. It yields one tuple at a time and never builds the full result.
- There is one
fillvaluefor all inputs. You cannot choose a different pad per input. - It works with any iterable, including generators and files.
Choosing a fill value that cannot collide
The default None is often a legitimate data value. If your data can contain None, you cannot tell a real None from padding. A private sentinel object avoids that, because nothing else in your data can be equal to it.
from itertools import zip_longest
def first_difference(left, right):
missing = object()
pairs = zip_longest(left, right, fillvalue=missing)
for index, (a, b) in enumerate(pairs):
if a != b:
return index
return None
print(first_difference([1, 2, 3], [1, 2, 3, 4]))
print(first_difference([1, 2, 3], [1, 2, 3]))
print(first_difference([1, None], [1]))This prints 3, then None, then 1. The third call is the important one. The second list is shorter, and the first list holds a real None at index 1. With the default fill, None != None would be False, and the function would wrongly report no difference. The sentinel makes the comparison correct.
Transposing ragged rows
zip(*rows) transposes a table, but it truncates ragged rows to the shortest. zip_longest(*rows) keeps the full shape.
from itertools import zip_longest
rows = [[1, 2, 3], [4, 5], [6]]
print(list(zip(*rows)))
print(list(zip_longest(*rows, fillvalue=0)))The first call prints [(1, 4, 6)]. The second prints [(1, 4, 6), (2, 5, 0), (3, 0, 0)]. The column-wise result is now complete.
Note that *rows unpacks the outer list into arguments, so all the rows exist in memory. This pattern is lazy in the columns it produces, but not in its input.
pairwise: overlapping neighbours
pairwise(iterable) yields each item together with the next one. It was added in Python 3.10.
from itertools import pairwise
print(list(pairwise([1, 4, 9, 16])))
print(list(pairwise('abc')))The first call prints [(1, 4), (4, 9), (9, 16)]. The second prints [('a', 'b'), ('b', 'c')]. An input with n items produces n - 1 pairs, so one item yields nothing and an empty input yields nothing. No error is raised in either case.
Typical uses
Differences between consecutive values:
from itertools import pairwise
temps = [20, 22, 21, 25, 30]
changes = [later - earlier for earlier, later in pairwise(temps)]
print(changes)This prints [2, -1, 4, 5].
Checking that data is sorted without sorting it:
from itertools import pairwise
def is_sorted(values):
return all(a <= b for a, b in pairwise(values))
print(is_sorted([1, 2, 2, 5]))
print(is_sorted([1, 3, 2]))This prints True, then False. Because all short-circuits, the check stops at the first out-of-order pair, and it works on a one-pass iterator.
Other common uses are finding gaps between timestamps, detecting where a value changes, and building edges from a path of nodes.
How it works, and the older recipe
pairwise holds only the previous item. It reads each input item once, so it works on iterators and uses constant memory. Before Python 3.10, the standard recipe combined tee and zip:
from itertools import tee
def pairwise_recipe(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
print(list(pairwise_recipe([1, 4, 9, 16])))This prints [(1, 4), (4, 9), (9, 16)]. Two independent copies of the stream are made, and the second is advanced by one item. zip then pairs item i with item i + 1. You may still see this recipe in older code. Prefer the built-in on Python 3.10 and later.
Beyond pairs: sliding windows
pairwise is a window of size 2. For a window of any size n, you can keep the last n items in a deque with a maximum length.
from collections import deque
from itertools import islice
def sliding_window(iterable, n):
it = iter(iterable)
window = deque(islice(it, n - 1), maxlen=n)
for item in it:
window.append(item)
yield tuple(window)
print(list(sliding_window('ABCDE', 3)))This prints [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')]. The islice call pre-loads the first n - 1 items. Each later item pushes the oldest one out of the deque, because maxlen=n discards from the opposite end. This uses constant memory and a single pass.
A moving average then needs one line:
averages = [sum(w) / len(w) for w in sliding_window([1, 2, 3, 4, 5], 3)]
print(averages)This prints [2.0, 3.0, 4.0].
Comparing the three pairing tools
| Tool | Stops when | Input count | Output tuple size | Typical use |
|---|---|---|---|---|
| `zip` | Shortest input ends | Any | One item per input | Aligned data of equal length |
| `zip(strict=True)` | Shortest ends; raises if lengths differ | Any | One item per input | Enforcing equal lengths |
| `zip_longest` | Longest input ends | Any | One item per input | Unequal data you must keep |
| `pairwise` | Input ends | Exactly one | Always 2 | Neighbour comparisons |
Gotchas
- Iterators are consumed.
pairwise(it)andzip_longest(a, b)read from their inputs as you iterate. If you pass an iterator and also read from it elsewhere, items go missing from one place or the other. - The result is single-use. Both functions return iterators. Calling
list()on the result twice gives the real data once and an empty list the second time. Nonepadding hides missing data. IfNonecan occur naturally, use a sentinel as shown above.- Version limits.
pairwiseneeds Python 3.10 or later, andzip(strict=True)needs 3.10 or later. On older versions, use theteerecipe and an explicit length check. - Mutable fill values are shared.
fillvalue=[]places the same list object in every padded slot. Mutating one changes them all. Use an immutable fill, or build fresh objects afterward.
Exercises
Exercise
What does list(zip_longest('ab', [1, 2, 3], fillvalue='-')) produce, and what would list(zip('ab', [1, 2, 3])) produce?
Show answer
The first gives [('a', 1), ('b', 2), ('-', 3)], because the shorter string is padded with '-'. The second gives [('a', 1), ('b', 2)], because zip stops at the shortest input and drops the 3.
Exercise
Write a function max_jump(values) that returns the largest absolute difference between consecutive items of an iterable of numbers, or None if there are fewer than two items. Use pairwise.
Show answer
from itertools import pairwise
def maxjump(values):
return max((abs(b - a) for a, b in pairwise(values)), default=None)
print(maxjump([3, 10, 4, 5])) # 7
print(max_jump([8])) # None
The default=None argument to max handles the case where pairwise yields nothing.
Exercise
Why is zip_longest(left, right) unsafe for finding differences between two lists that may contain None, and how do you fix it?
Show answer
The default fill value is None, so a padded slot looks identical to a real None in the data, and a comparison can wrongly report equality. Pass a private sentinel such as fillvalue=object() that cannot equal any real item.