What is the itertools.tee() method in Python?

Note: itertools is a module in Python that provides functions. These functions help in iterating through iterables.

The tee() method in the itertools module gets independent iterators for the given iterable. The number of iterators to return is specified as a function argument. The tee iterators do not ensure thread safety.

Syntax

itertools.tee(iterable, n=2)

Parameters

  • iterable: The iterable for which iterators need to be returned.
  • n: The number of iterators to return.

Example 1

import itertools
lst = ['a', 'b', 'c']
iter_1, iter_2 = itertools.tee(lst, 2)
print("Iterator 1 - ", list(iter_1))
print("Iterator 1 - ", list(iter_1))
print("Iterator 2 - ", list(iter_2))

Explanation

  • Line 1: We import the itertools module.
  • Line 3: We define a list of characters called lst.
  • Line 5: Two iterators are obtained from lst using the tee() method where lst and 2 (n) are passed as arguments.
  • Lines 7–9: The iterators obtained are printed by converting them to list.

The output shows that line 8 prints an empty list, indicating that iter_1 is already traversed in line 7.

Coding example 2

import itertools
lst = range(4, 10)
iter_1, iter_2 = itertools.tee(lst, 2)
print("Iterator 1 - ", list(iter_1))
print("Iterator 1 - ", list(iter_1))
print("Iterator 2 - ", list(iter_2))

Explanation

  • Line 1: We import the itertools module.
  • Line 3: We define the iterable of numbers called lst ranging from 4 to 10. We use the range() method for this.
  • Line 5: Two iterators are obtained from lst using the tee() method where lst and 2 (n) are passed as arguments.
  • Lines 7–9: The iterators obtained are printed by converting them to list.

The output shows that line 8 prints an empty list, indicating that iter_1 is already traversed in line 7.

Free Resources