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.
itertools.tee(iterable, n=2)
iterable
: The iterable for which iterators need to be returned.n
: The number of iterators to return.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))
itertools
module.lst
.lst
using the tee()
method where lst
and 2
(n
) are passed as arguments.list
.The output shows that line 8 prints an empty list, indicating that iter_1
is already traversed in line 7.
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))
itertools
module.lst
ranging from 4
to 10
. We use the range()
method for this.lst
using the tee()
method where lst
and 2
(n
) are passed as arguments.list
.The output shows that line 8 prints an empty list, indicating that iter_1
is already traversed in line 7.