Note
Python - tee() - Duplicate an iterable into multiple iterators
Overview of the Python tee() function. Duplicate your iterable multiple times in one object.
tee(iterable, n) lets you "copy" or "duplicate" your iterable n times.
It returns a tuple with lazy iterators.
It's useful if you want to iterate over your iterable several times, while preserving lazy evaluation.
tee needs to be imported from itertools
Please take a look at examples below to better understand tee():
from itertools import tee
l1 = [1, 2, 3]
# Create three independent iterators from l1
three_l1 = tee(l1, 3) # (first_l1_iterator, second_l1_iterator, third_l1_iterator)
# (<itertools._tee object at 0x10>, <itertools._tee object at 0x10>, <itertools._tee object at 0x10>)
for a, b, c in three_l1: # Unpack the tuple of iterators
print(a, b, c) # 1 2 3
Output:
1 2 3
1 2 3
1 2 3
Note that first_l1_iterator etc. are no longer lists. They are lazy iterators now.
Unpacking tee() Iterators Using *
from itertools import tee
l2 = ["a", "b", "c"]
# Create three independent iterators from l2
three_l2 = tee(l2, 3) # (first_l2_iterator, second_l2_iterator, third_l2_iterator)
# (<itertools._tee object at 0x10>, <itertools._tee object at 0x10>, <itertools._tee object at 0x10>)
for iterator in three_l2:
print(*iterator) # a b c; Unpack the iterator from tuple of iterators here
Output:
a b c
a b c
a b c
Key Points to Remember about the tee() Function
-
Lazy and Independent Iterators:
tee()provides multiple, independent iterators that consume elements lazily. -
Potential Memory Overhead: While
tee()enables multiple passes over an iterable, it can increase memory usage due to caching. -
Single Use: Avoid using the original iterator after applying
tee(), as doing so can cause unexpected behavior in the independent iterators.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!
You might also be interested in:
- 💡 Arrays in Computer Science and Python - An overview with space and time complexities
- 💡 Python - chain() - Join multiple iterables lazily
- 💡 Python - List, Tuple, and Set Comprehensions - Simplify iterable transformations
- 💡 Python - sum() - Add all values in an iterable
- 💡 Python - reduce() - Reduce an iterable to a single value