CKTIS / Python
itertools.pairwise
Yields overlapping pairs of neighboring input items.
Version: Python 3.14; repository image, production runtime not attested
Syntax
itertools.pairwise(iterable, /)Yields overlapping pairs of neighboring input items.
An input shorter than two elements produces no pairs.
Each item after the first pairs with its predecessor. From 3, 8, 4 the pairs are (3, 8) and (8, 4); they overlap at 8. A finite input of n items gives max(n−1, 0) pairs. One item has no neighbor, so the second output is empty.
import itertools as I
assert list(I.pairwise([3, 8, 4])) == [(3, 8), (8, 4)]
assert not list(I.pairwise([])) and not list(I.pairwise([3]))
Examples
import itertools as I
print(list(I.pairwise([3, 8, 4])))
print(list(I.pairwise([3])))
Result
[(3, 8), (8, 4)] []
Each item after the first pairs with its predecessor. From 3, 8, 4 the pairs are (3, 8) and (8, 4); they overlap at 8. A finite input of n items gives max(n−1, 0) pairs. One item has no neighbor, so the second output is empty.