The Python itertools.tee() function is used to create multiple independent iterators from a single iterable. These iterators share the same data but can be iterated over separately.
This function is useful when an iterable needs to be consumed multiple times in different parts of a program without reconstructing it.
SyntaxFollowing is the syntax of the Python itertools.tee() function −
itertools.tee(iterable, n=2)Parameters
This function accepts the following parameters −
This function returns a tuple containing n independent iterators.
Example 1Following is an example of the Python itertools.tee() function. Here, we create two iterators from a single iterable and iterate over them independently −
import itertools numbers = [1, 2, 3, 4, 5] iter1, iter2 = itertools.tee(numbers) print("Iterator 1:") for num in iter1: print(num) print("Iterator 2:") for num in iter2: print(num)
Following is the output of the above code −
Iterator 1: 1 2 3 4 5 Iterator 2: 1 2 3 4 5Example 2
Here, we create three independent iterators and use them separately to process data −
import itertools data = ["apple", "banana", "cherry"] iter1, iter2, iter3 = itertools.tee(data, 3) print("First iterator:", list(iter1)) print("Second iterator:", list(iter2)) print("Third iterator:", list(iter3))
Output of the above code is as follows −
First iterator: ['apple', 'banana', 'cherry'] Second iterator: ['apple', 'banana', 'cherry'] Third iterator: ['apple', 'banana', 'cherry']Example 3
Now, we use itertools.tee() function with a filtering operation. We first split an iterator and apply different processing techniques on each copy −
import itertools numbers = [10, 20, 30, 40, 50] iter1, iter2 = itertools.tee(numbers) # Use one iterator to find sum sum_values = sum(iter1) print("Sum of numbers:", sum_values) # Use second iterator to find maximum value max_value = max(iter2) print("Maximum value:", max_value)
The result obtained is as shown below −
Sum of numbers: 150 Maximum value: 50Example 4
When using itertools.tee() function, consuming one iterator completely affects the others. To avoid unexpected behavior, convert iterators to lists if necessary −
import itertools data = [1, 2, 3, 4] iter1, iter2 = itertools.tee(data) print("Using first iterator:") for num in iter1: print(num) print("Using second iterator:") print(list(iter2))
The result produced is as follows −
Using first iterator: 1 2 3 4 Using second iterator: [1, 2, 3, 4]
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4