itertools.tee Splits One Iterator In Two
tee clones a single-pass iterator into independent cursors that each see the full stream, buffering whatever one branch reads ahead of the other.
Code
from itertools import tee
events = iter(["boot", "login", "deploy", "logout"])
# tee splits one single-pass iterator into independent cursors.
historian, auditor = tee(events)
# Branch 1 pulls the first two events off its own cursor...
print("historian:", [next(historian) for _ in range(2)])
# ...while branch 2 still yields the full stream: tee buffers items
# one branch reads until the other catches up.
print("auditor:", list(auditor))
# tee itself exhausts the source iterator; drive the branches, not the parent.
print("parent remaining:", list(events))
# Drain order does not matter: whatever one branch read is buffered for the other.
a, b = tee([1, 2, 3, 4, 5])
print("b fully drained:", list(b))
print("a still intact:", list(a))Output
Captured from a sandboxed run of this snippet in the build pipeline.
historian: ['boot', 'login']
auditor: ['boot', 'login', 'deploy', 'logout']
parent remaining: []
b fully drained: [1, 2, 3, 4, 5]
a still intact: [1, 2, 3, 4, 5]What the code does
The file’s state is a handful of top-level bindings: events.
What to watch for
- No package manager involved — every call resolves to a built-in API.
Where you would use it
Output lines are prefixed (historian:, auditor:, parent remaining:), making each step’s effect easy to spot.
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `itertools`. Its state lives in module-level bindings: `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.