Sub topic 12
Copying an iterator with tee
This chapter assumes you know that an iterator is used up after one pass, and that you can read basic itertools code such as islice. If an iterator is exhausted, list(it) returns [] the second time. tee is the tool for the case where you need to read the same stream more than once.
What tee does
itertools.tee(iterable, n=2) returns n independent iterators over one source. Each copy yields every item of the source, in order, at its own pace.
from itertools import tee
a, b = tee(iter([1, 2, 3]))
print(next(a), next(b), list(a))This prints 1 1 [2, 3]. Advancing a does not advance b. Both copies see 1 first.
How it works internally
The source is only read once. When one copy asks for an item the others have not seen yet, tee pulls it from the source and stores it in a shared buffer. Each copy remembers its own position in that buffer. An item is dropped once every copy has passed it.
This design has two consequences:
- Memory use equals the gap between the fastest and slowest copy.
- The source is consumed lazily, so
teeworks on generators and other one-shot streams.
A practical use: two passes over a stream
Suppose you want the largest value and the average of a generator. Without tee you would have to build a list. With tee, you can read the stream twice:
from itertools import tee
def readings():
for value in (3, 8, 5, 6):
yield value
first, second = tee(readings())
largest = max(first)
average = sum(second) / 4
print(largest, average)This prints 8 5.5. Because max(first) runs to the end before second starts, tee buffers all four values. Here tee saves you from writing list(...), but it uses the same memory as a list would.
Pitfall 1: unbounded buffers
If one copy is consumed far ahead of the others, the buffer grows with the gap.
from itertools import tee
a, b = tee(range(5))
print(list(a))
print(list(b))This prints [0, 1, 2, 3, 4] twice. The five items sat in the buffer between the two calls. On a very large or infinite stream, this pattern exhausts memory. If you need to run through the data twice and it fits in memory, list() is simpler and just as costly. tee pays off when the copies advance close together, as in lock-step.
Pitfall 2: using the original iterator
After calling tee, do not touch the source iterator. Items you pull from it directly never reach the copies.
from itertools import tee
it = iter([1, 2, 3])
a, b = tee(it)
print(next(it))
print(list(a))This prints 1 and then [2, 3]. The copy a lost the first item because the original iterator was advanced behind its back.
Pitfall 3: threads
The copies returned by tee are not thread-safe. Do not consume them from different threads without your own locking.
When to prefer something else
| Situation | Better choice |
|---|---|
| Data is small and you need several passes | `list(data)` |
| Copies advance in lock-step | `tee` |
| One copy runs far ahead of the other | `list(data)` |
| You can recreate the source cheaply | Call the generator function again |
Exercise
A program calls a, b = tee(huge_generator()), then runs sum(a) and afterwards max(b). Why is this a poor use of tee, and what would you change?
Show answer
sum(a) consumes the whole stream before b reads anything, so tee buffers every item, which is as much memory as a list. If the data fits in memory, use list(). If it does not, compute the sum and the maximum in one loop, or call the generator function a second time to get a fresh stream.