Python Snippet

Pairwise Iteration

Difficulty: Easy

`itertools.pairwise` (Python 3.10+) yields successive overlapping pairs from any iterable. It replaces the classic `zip(seq, seq[1:])` and the `tee` recipe with a single, lazy, memory-flat call. This entry covers the basic pattern, the manual fallback for older Python, and a tiny example: detecting monotonic runs.

Code Snippets
/

Pairwise Iteration

Pairwise Iteration

`itertools.pairwise` (Python 3.10+) yields successive overlapping pairs from any iterable. It replaces the classic `zip(seq, seq[1:])` and the `tee` recipe with a single, lazy, memory-flat call. This entry covers the basic pattern, the manual fallback for older Python, and a tiny example: detecting monotonic runs.

Python
Easy
3 snippets
py-itertools
py-generators
iterators
sliding-window

1,058 views

27

pairwise(iterable) yields (s0, s1), (s1, s2), (s2, s3), ... until the source has fewer than two items left. It works on any iterable (list, tuple, generator, file object), not just sequences, and it does not rebuild internal state between iterations. Use it whenever a calculation reads two adjacent items at a time: deltas, ratios, monotonic checks, edge construction from a path. It costs O(n) time and O(1) extra memory regardless of input size.