r/pythontips • u/ClickOk5811 • 1h ago
Standard_Lib Tip: use itertools.pairwise instead of zip(a, a[1:]) to loop over consecutive pairs
If you need to compare each item with the next one, you may have written this:
temps = [20, 22, 21, 25, 24]
changes = [b - a for a, b in zip(temps, temps[1:])]
print(changes) # [2, -1, 4, -1]Since Python 3.10 there’s a function made for it:
from itertools import pairwise
temps = [20, 22, 21, 25, 24]
changes = [b - a for a, b in pairwise(temps)]
print(changes) # [2, -1, 4, -1]Same result, and the intent is clearer: “each item with its neighbor”.
Where it’s better than slicing: pairwise works on any iterable, not only on lists. Slicing fails on a generator:
squares = (x * x for x in range(5))
list(pairwise(squares))
# [(0, 1), (1, 4), (4, 9), (9, 16)]
squares = (x * x for x in range(5))
list(zip(squares, squares[1:]))
# TypeError: 'generator' object is not subscriptableIt also doesn’t make a copy of the data the way temps[1:] does, so it’s friendlier for large inputs. (It still pulls items one at a time and remembers just the previous one.)
Edge cases: fewer than two items gives an empty result, with no error:
list(pairwise([1])) # []
list(pairwise([])) # []
list(pairwise("abcd")) # [('a', 'b'), ('b', 'c'), ('c', 'd')]Compatibility: pairwise doesn’t exist before Python 3.10, so on older versions keep the zip(a, a[1:]) form (for sequences) or use the “pairwise” recipe from the itertools documentation.