What is the itertools.tee() method in Python?
Note:
itertoolsis 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 itertoolslst = ['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
itertoolsmodule. - Line 3: We define a list of characters called
lst. - Line 5: Two iterators are obtained from
lstusing thetee()method wherelstand2(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 itertoolslst = 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
itertoolsmodule. - Line 3: We define the iterable of numbers called
lstranging from4to10. We use therange()method for this. - Line 5: Two iterators are obtained from
lstusing thetee()method wherelstand2(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.