Advertisement
Advanced Python, Iterators & the Iterator Protocol

How does itertools.tee let you iterate over the same iterator multiple times independently?

Short answer

tee(iterable, n) splits a single iterator into n independent iterators that can be advanced separately, internally buffering values that one consumer has read but another hasn't yet.

Save Python mock interview
Advertisement
AModel answer
tee(iterable, n) splits a single iterator into n independent iterators that can be advanced separately, internally buffering values that one consumer has read but another hasn't yet. This is essential because a normal iterator is single-pass and consumed once read; tee avoids materializing the whole sequence into a list just to reuse it, though it does use memory proportional to how far apart the consumers get.
import itertools

it = iter([1,2,3,4])
a, b = itertools.tee(it, 2)
print(next(a))  # 1
print(list(b))  # [1,2,3,4]
print(list(a))  # [2,3,4]
Real-world example
A streaming analytics job uses tee to feed the same event stream into both a real-time alerting consumer and a slower batch-aggregation consumer.
Likely follow-ups
  • What happens to memory if one branch lags far behind the other?
  • When is converting to a list simpler than tee?
Related topics