The itertools.tee function in Python’s itertools module returns multiple independent iterators (or "tees") from a single input iterable. It is useful when you need to iterate over the same iterable in parallel, without consuming it.
Table of Contents
- Introduction
itertools.teeFunction Syntax- Examples
- Basic Usage
- Using Multiple Tees
- Iterating in Parallel
- Combining with Other Itertools Functions
- Real-World Use Case
- Conclusion
Introduction
The itertools.tee function creates multiple independent iterators from a single input iterable. This allows you to iterate over the same sequence multiple times simultaneously, without having to store the entire sequence in memory.
itertools.tee Function Syntax
Here is how you use the itertools.tee function:
import itertools
iterators = itertools.tee(iterable, n=2)
Parameters:
iterable: The input iterable to be duplicated.n: Optional. The number of independent iterators to return (default is 2).
Returns:
- A tuple of
nindependent iterators.
Examples
Basic Usage
Create two independent iterators from a single list.
Example
import itertools
data = [1, 2, 3, 4, 5]
it1, it2 = itertools.tee(data)
print(list(it1)) # Output: [1, 2, 3, 4, 5]
print(list(it2)) # Output: [1, 2, 3, 4, 5]
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Using Multiple Tees
Create three independent iterators from a single list.
Example
import itertools
data = [1, 2, 3, 4, 5]
it1, it2, it3 = itertools.tee(data, 3)
print(list(it1)) # Output: [1, 2, 3, 4, 5]
print(list(it2)) # Output: [1, 2, 3, 4, 5]
print(list(it3)) # Output: [1, 2, 3, 4, 5]
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Iterating in Parallel
Iterate over the same sequence in parallel using two iterators.
Example
import itertools
data = [1, 2, 3, 4, 5]
it1, it2 = itertools.tee(data)
for x, y in zip(it1, it2):
print(f"it1: {x}, it2: {y}")
Output:
it1: 1, it2: 1
it1: 2, it2: 2
it1: 3, it2: 3
it1: 4, it2: 4
it1: 5, it2: 5
Combining with Other Itertools Functions
Combine tee with filter to create multiple filtered iterators.
Example
import itertools
data = range(10)
it1, it2 = itertools.tee(data)
evens = filter(lambda x: x % 2 == 0, it1)
odds = filter(lambda x: x % 2 != 0, it2)
print(list(evens)) # Output: [0, 2, 4, 6, 8]
print(list(odds)) # Output: [1, 3, 5, 7, 9]
Output:
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
Real-World Use Case
Splitting an Iterator for Multiple Passes
Use tee to split an iterator for multiple passes over the data.
Example
import itertools
def process(data):
it1, it2 = itertools.tee(data)
print("First pass:")
for item in it1:
print(item)
print("Second pass:")
for item in it2:
print(item)
data = [1, 2, 3, 4, 5]
process(data)
Output:
First pass:
1
2
3
4
5
Second pass:
1
2
3
4
5
Conclusion
The itertools.tee function is used for creating multiple independent iterators from a single input iterable. It allows you to iterate over the same sequence in parallel, making it useful for various data processing tasks that require multiple passes over the data.