On this page
itertools.tee
Prev: itertools.takewhile | Up: itertools | Next: itertools.zip_longest
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.tee
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import tee
Signature & Overview
itertools.tee(iterable, n=2, /)
Returns a tuple of n independent iterators.
Usage
from itertools import tee
it1, it2 = tee((x * 10 for x in range(3)), 2)
assert list(it1) == [0, 10, 20]
assert list(it2) == [0, 10, 20]
Gotchas
- Never touch the original iterator after calling
tee(): Advancing the original skips items for all forked copies. - Hidden memory buffer: If one branch races far ahead of another,
tee()buffers every unread item in RAM—if you need full multi-pass access,tuple(it)is simpler and often cheaper. - Not thread-safe: Do not consume forked
teeiterators concurrently from different threads.
REPL Inspect
from itertools import tee
help(tee)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/takewhile Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/zip_longest Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib