Python 3.10+itertoolsfunction
itertools.pairwise
itertools
Successive overlapping pairs: (s0,s1), (s1,s2), … (3.10+).
Syntax
itertools.pairwise(iterable)
Unlike the old zip(seq, seq[1:]) trick, pairwise works on any iterable — generators and infinite streams included — because it lazily keeps only the previous element around. With fewer than two input items it yields nothing.
Examples
import itertools
print(list(itertools.pairwise([1, 2, 3, 4]))) # → [(1, 2), (2, 3), (3, 4)]
print(list(itertools.pairwise('abc'))) # → [('a', 'b'), ('b', 'c')]
print([b - a for a, b in itertools.pairwise([10, 13, 12, 20])]) # → [3, -1, 8]
print(all(a <= b for a, b in itertools.pairwise([1, 2, 2, 5]))) # → True
print(list(itertools.pairwise([7]))) # → []
See also
Open in the full glossarydocs.python.orgReport an inaccuracy