The itertools module provide a number of useful functions for working with iterables through iterators.
The tee()
function in the module creates a number of iterators for the specified iterable object. Essentially, the function creates a tuple of n
independent iterators from a single iterable.
tee(iterable, n = 2)
iterable |
Required. The iterable to create the iterators for. |
n |
Optional. The number of independent iterators to create. Defaults to 2. |
The function returns a tuple of n
independent iterators.
#import the tee function
from itertools import tee
data = [0, 2, 4, 6, 8, 10]
#create two iterators for data
its = tee(data)
print(its)
for i in its:
print(*i)
In the following example a non-default parameter n
is given.
#import the tee function
from itertools import tee
data = ['Python', 'Java', 'C++']
#create two iterators for data
its = tee(data, 4)
for i in its:
print(*i)