Python itertools.tee() Function



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.

Syntax

Following is the syntax of the Python itertools.tee() function −

itertools.tee(iterable, n=2)

Parameters

This function accepts the following parameters −

  • iterable: The input iterable that needs to be duplicated.
  • n (optional): The number of independent iterators to create (default is 2).

Return Value

This function returns a tuple containing n independent iterators.

Example 1

Following is an example of the Python itertools.tee() function. Here, we create two iterators from a single iterable and iterate over them independently −

Open Compiler
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
5

Example 2

Here, we create three independent iterators and use them separately to process data −

Open Compiler
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 −

Open Compiler
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: 50

Example 4

When using itertools.tee() function, consuming one iterator completely affects the others. To avoid unexpected behavior, convert iterators to lists if necessary −

Open Compiler
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
Advertisements