How to Create a Pairwise Generator with zip and tee in Python

Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.

Easy Python 3.10+ Aug 9, 2026 Comprehensions & generators 15 views 0 copies

Python code

14 lines
Python 3.10+
from itertools import tee


def pairwise(iterable):
    """Yield successive overlapping pairs from iterable."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5]
    print(list(pairwise(values)))
    print(list(pairwise("hello")))

Output

stdout
[(1, 2), (2, 3), (3, 4), (4, 5)]
[('h', 'e'), ('e', 'l'), ('l', 'l'), ('l', 'o')]

How it works

The tee function duplicates the iterator into two independent streams, and next(b, None) advances one of them by one element. zip then pairs corresponding elements from both streams, producing overlapping pairs without loading the entire iterable into memory. For a single-element or empty iterable, the generator yields nothing because zip stops at the shorter stream. This pattern is lazy, so it works with infinite iterables only if you stop consuming it at some point.

Common mistakes

  • Using `next(b)` without a default, which raises StopIteration on empty iterables.
  • Forgetting that the result is a generator, not a list, and trying to access it multiple times.
  • Applying this to a one-shot iterator (like a file object) without realizing the original is consumed.
  • Not using `from itertools import tee` and accidentally reusing the same iterator in `zip`.

Variations

  1. Use the built-in `itertools.pairwise` in Python 3.10+ for the same effect without custom code.
  2. Enforce a tuple return by wrapping with `tuple(pairwise(items))` if a reusable sequence is needed.

Real-world use cases

  • Comparing consecutive sensor readings in an IoT data pipeline to detect anomalies or rate changes.
  • Sliding-window feature extraction for time-series data in machine learning preprocessing.
  • Detecting adjacent duplicate entries in a log file or user activity stream for cleanup tasks.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.