Share an Iterator with tee
Core idea
tee(iterable, n=2) creates n iterators over the same source. They can advance at different rates; values read by a leading branch must remain available for slower branches. This may require memory proportional to the lag. tee does not copy the elements themselves.
from itertools import teeleft, right = tee(iter([7, 9, 12]))print(next(left), next(left))print(next(right))print(list(left), list(right))The branches have separate positions but share one upstream source.
Observe lazy source reads
from itertools import teedef readings(): for value in [4, 8]: print("read", value) yield valuea, b = tee(readings())print(next(a))print(next(b))The upstream read occurs once. The second branch reuses the saved value.
Shared mutable item
from itertools import teea, b = tee([[3]])next(a).append(5)print(next(b))The saved element is a reference to the same list.
Common mistake
Do not advance the original iterator after tee splits it. tee branches are not thread-safe; if one branch consumes most data before the other starts, a list may be simpler and faster for finite input.
Practice
Split a four-item iterator into two branches. Consume three items from the first and one from the second. Predict the next value of each, and explain which values must still be retained.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Share an upstream iterator
Check your understanding of tee and iterator sharing.
What is printed?
from itertools import teea, b = tee([2, 3, 4])print(next(a), next(a), next(b))What is printed?
from itertools import teea, b = tee([{}])print(next(a) is next(b))What is printed?
from itertools import tee, islicea, b = tee([8, 9])print(list(islice(a, 1)), list(b))When can tee require substantial auxiliary storage?