Create independent iterators from one iterator source.
What You Will Learn
tee(iterable, n=2) buffers items when derived iterators advance at different speeds. Avoid large gaps between consumers: the cache can grow. The returned iterators are not threadsafe.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from itertools import tee
first, second = tee(iter([1, 2, 3]))
print(next(first))
print(list(second))
print(list(first))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: itertools.
- The variable (first, second) holds the result of tee(iter([1, 2, 3])). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
1
[1, 2, 3]
[2, 3]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Use two iterator consumers with different processing speeds.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Treating tee() as a free full copy of a stream without considering memory buffering.
- Overlooking this documented constraint: the returned iterators are not threadsafe.
Key Takeaways
- Create independent iterators from one iterator source.
- tee(iterable, n=2) buffers items when derived iterators advance at different speeds.
- Apply this operation only after checking the assumptions and input conditions shown in the example.