Sub topic 12
Copying an Iterator with tee
This chapter assumes you know Python functions, loops and comprehensions, and that you have met iterators, next() and the idea that an iterator is used up after one pass. Generators and yield help but are not required.
The problem: one pass only
An iterator can be read once. When you loop over it, each item is handed out and then gone. Sometimes you need two passes over the same stream. For example, you may want to compute an average and then compare each value to it, or look ahead at the next item without losing your place.
The first idea is to copy the iterator with list(). That works, but it stores every item in memory, which defeats the purpose of lazy iteration. Another idea is copy.copy(). It does not work reliably for iterators, and it cannot copy a generator at all.
itertools.tee solves this. It takes one iterable and returns several independent iterators. Each of them yields the same items in the same order.
from itertools import tee
a, b = tee(iter([1, 2, 3]))
print(next(a), next(b), list(a))This prints 1 1 [2, 3]. The iterator a advanced one step, b advanced one step on its own, and list(a) collected what remained for a. The iterator b still has [2, 3] waiting.
Signature
tee(iterable, n=2)iterableis any iterable.teecallsiter()on it for you.nis how many independent iterators to return. The default is 2.- The result is a tuple of
niterators.
Because the result is a tuple, you can unpack it when you know n, or index into it when n is a variable.
from itertools import tee
copies = tee("abc", 3)
print(len(copies))
print([list(c) for c in copies])This prints 3 and then [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]. Each copy reads the whole string independently.
How tee works inside
tee does not duplicate the source. It reads from the source once and keeps a shared buffer of items that at least one copy has not yet consumed.
- A copy asks for its next item.
- If a faster copy already pulled that item from the source, the slower copy reads it from the buffer.
- If no copy has pulled it yet,
teetakes it from the source and adds it to the buffer. - When every copy has passed an item,
teediscards it.
The buffer therefore holds the distance between the fastest and the slowest copy. This distance explains everything about when tee is cheap and when it is costly.
Cheap case: copies stay close together
If the copies advance in step, the buffer stays small, often one item. The classic example is pairwise, which the itertools documentation implements with tee.
from itertools import tee
def my_pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
print(list(my_pairwise([1, 4, 9, 16])))This prints [(1, 4), (4, 9), (9, 16)]. The copy b is moved one step ahead with next(b, None). Then zip pulls one item from each copy per step. The gap between the copies is always one item, so memory use is constant. The second argument None stops next from raising StopIteration when the input is empty.
On Python 3.10 and later, use the built-in pairwise instead. This version only shows how it works.
Costly case: one copy runs far ahead
If one copy consumes much more than the other, the buffer grows to hold everything in between. In the extreme case, you read one copy to the end before touching the other. The buffer then holds the entire stream, which is the same as calling list().
from itertools import tee
def numbers():
for i in range(5):
print("produced", i)
yield i
a, b = tee(numbers())
print("sum a:", sum(a))
print("list b:", list(b))The output is:
produced 0
produced 1
produced 2
produced 3
produced 4
sum a: 10
list b: [0, 1, 2, 3, 4]The generator runs only once, as each produced line appears a single time. All five values were stored in the buffer while sum(a) ran, and then b replayed them. For five items that is harmless. For a stream of millions of items, this pattern uses as much memory as a list. If you will consume the copies one after another, list() is simpler and no slower.
Do not use the original after tee
Once you pass an iterator to tee, treat the original as owned by tee. If you advance the original directly, the items it yields never reach the buffer. The copies then miss them.
from itertools import tee
source = iter([1, 2, 3, 4])
a, b = tee(source)
print(next(source))
print(list(a))
print(list(b))This prints 1, then [2, 3, 4], then [2, 3, 4]. The item 1 was taken by the direct next(source) call, so neither copy saw it. The copies agree with each other, but they no longer match the data you started with. Always use only the copies after calling tee.
A related habit is to rebind the name:
from itertools import tee
data = iter([1, 2, 3])
data, backup = tee(data)
print(list(data), list(backup))This prints [1, 2, 3] [1, 2, 3]. Rebinding data removes access to the original iterator by name, which prevents the mistake above.
Peeking ahead without losing items
A common use of tee is to look at upcoming items while keeping the stream whole.
from itertools import islice, tee
stream = iter(range(10, 20))
stream, lookahead = tee(stream)
print(list(islice(lookahead, 3)))
print(next(stream))This prints [10, 11, 12] and then 10. The lookahead copy read three items to inspect them. The main stream copy has not moved, so it still starts at 10. The buffer holds three items until stream catches up.
Thread safety
The tee iterators are not thread-safe. Using several copies from different threads at the same time can raise RuntimeError or give wrong results, even if the source itself is safe. If you need to share a stream between threads, use a queue.Queue or give each thread its own source.
tee with generators and side effects
Because tee reads the source only once, side effects in a generator happen once, not once per copy. That is often what you want, such as reading a file or a network response only once. It also means the timing of side effects depends on which copy is read first, as the produced output above shows. If your generator has side effects, be aware that they happen when the leading copy asks for an item, not when each copy does.
When not to use tee
| Situation | Better choice |
|---|---|
| The source is a list, tuple, string or range | Iterate over the source again. These can be iterated any number of times. |
| You will read one copy completely, then the other | `list()` or `tuple()`. |
| Copies advance far apart | `list()`, so the memory cost is explicit. |
| You can reopen the source cheaply, such as a file | Open it twice. |
| You need random access or indexing | A list. |
| Use from several threads | `queue.Queue` or separate sources. |
tee is most useful when the source is a true one-pass stream, such as a generator, a socket or a pipeline, and when the copies stay within a few items of each other.
Summary
tee(iterable, n=2)returnsnindependent iterators over one source.- It reads the source once and buffers the items that the slowest copy has not yet seen.
- Memory use equals the gap between the fastest and the slowest copy.
- Do not touch the original iterator after calling
tee. - Copies are not thread-safe.
- If you will drain one copy before starting another, a list is simpler.
Exercise
The code below builds two copies of a generator and sums one before reading the other. The generator yields 1,000,000 values. Explain how much memory tee needs here and what you would write instead.
from itertools import tee
a, b = tee(x * x for x in range(1000000))
total = sum(a)
items = list(b)
Show answer
Because sum(a) finishes before b is read, the copy a runs a million items ahead of b. tee must buffer all one million values, so memory use is about the same as a list. Writing items = list(x * x for x in range(1_000_000)) and then total = sum(items) gives the same result with clearer cost and no tee. Alternatively, run through the stream once and compute the sum and the list together, for example by building the list and calling sum on it.
Exercise
Write a function deltas(iterable) that returns an iterator of the differences between each item and the one before it, using tee and zip. For [1, 4, 9, 16] it should give [3, 5, 7]. Why does the buffer stay small?
Show answer
from itertools import tee def deltas(iterable): a, b = tee(iterable) next(b, None) return (y - x for x, y in zip(a, b)) print(list(deltas([1, 4, 9, 16]))) This prints [3, 5, 7]. The copy b starts one item ahead of a, and zip pulls one item from each per step. The gap never exceeds one item, so the buffer holds at most one value.
Exercise
After running source = iter([1, 2, 3, 4]); a, b = tee(source); next(source), what do list(a) and list(b) return, and why is this a bug in most programs?
Show answer
Both return [2, 3, 4]. The direct next(source) call took the item 1 from the source without going through tee's buffer, so neither copy saw it. The copies agree with each other but have silently lost data. After calling tee, use only the returned copies.