CKTIS / Python
itertools.tee
Creates independent iterators over a single underlying input.
Version: Python 3.14; repository image, production runtime not attested
Syntax
itertools.tee(iterable, n=2, /)Creates independent iterators over a single underlying input.
When consumers advance at different rates the iterator must buffer values for the slower consumer.
Each returned iterator has a separate position in one source stream. Advancing a reads 3 and buffers it for b, which can still read both 3 and 5. Then a has only 5 remaining. The memory needed for buffering grows with the gap between consumers.
import itertools as I
a, b = I.tee(iter([3, 5]))
assert next(a) == 3 and list(b) == [3, 5] and list(a) == [5]
Examples
import itertools as I
a, b = I.tee(iter([3, 5]))
print(next(a))
print((list(b), list(a)))
Result
3 ([3, 5], [5])
Each returned iterator has a separate position in one source stream. Advancing a reads 3 and buffers it for b, which can still read both 3 and 5. Then a has only 5 remaining. The memory needed for buffering grows with the gap between consumers.