Batu Lab NotesPractical developer guides

Observe independent positions after splitting an iterator with tee

By Batu · English technical notes

Observe independent positions after splitting an iterator with tee

Yes: itertools.tee() gives each returned branch its own observable position. Advancing left does not move right to the same item. The experiment starts with iter(['A', 'B', 'C']), advances left twice, and then reads right once. Although left has reached B, right still returns A.

The five-line transcript deliberately groups each branch’s remaining reads on its final two lines. It makes the positions visible without relying on implementation details or making a memory-size claim. The assertions establish the intended sequence: left produces A, B, then C; right independently produces A, B, then C.

This is useful when two consumers need the same ordered input but may progress at different times. Treat that divergence as an ownership decision: a consumer cannot assume another branch has already consumed, acknowledged, or skipped a value merely because it has done so itself. Conversely, tee() is not a shared cursor; use one iterator only when all readers truly need one shared position.

tee() is part of the Python standard library and is available on supported Python 3 versions. The official documentation describes its result as independent iterators and also notes a separate threading limitation, so this small sequential example should not be generalized into concurrent access guidance. Python itertools.tee() documentation

AI assistance disclosure: This article was prepared with AI assistance and checked with the synthetic assertions shown below.

from itertools import tee

source = iter(["A", "B", "C"])
left, right = tee(source)

left_first = next(left)
left_second = next(left)
right_first = next(right)
left_remaining = list(left)
right_remaining = list(right)

assert (left_first, left_second, left_remaining) == ("A", "B", ["C"])
assert (right_first, right_remaining) == ("A", ["B", "C"])

print(f"1 left position 1: {left_first}")
print(f"2 left position 2: {left_second}")
print(f"3 right position 1: {right_first}")
print(f"4 left remaining: {left_remaining}")
print(f"5 right remaining: {right_remaining}")
1 left position 1: A
2 left position 2: B
3 right position 1: A
4 left remaining: ['C']
5 right remaining: ['B', 'C']