Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython – Itertools.tee()

Python – Itertools.tee()

In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse().

Note: For more information, refer to Python Itertools

tee() function

This iterator splits the container into a number of iterators mentioned in the argument.

Syntax:

tee(iterator, count)

Parameter: This method contains two arguments, the first argument is iterator and the second argument is a integer.
Return Value: This method returns the number of iterators mentioned in the argument.

Example 1:




# Python code to demonstrate the working of tee() 
    
# importing "itertools" for iterator operations 
import itertools 
    
# initializing list  
li = [2, 4, 6, 7, 8, 10, 20
    
# storing list in iterator 
iti = iter(li) 
    
# using tee() to make a list of iterators 
# makes list of 3 iterators having same values. 
it = itertools.tee(iti, 3
    
# printing the values of iterators 
print ("The iterators are : "
for i in range (0, 3): 
    print (list(it[i])) 


Output:

The iterators are : 
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]

Example 2:




# Python code to demonstrate the working of tee() 
    
# importing "itertools" for iterator operations 
import itertools
    
    
# using tee() to make a list of iterators 
  
iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2)
    
# printing the values of iterators 
print (list(iterator1)) 
print (list(iterator1)) 
print (list(iterator2)) 


Output:

[1, 2, 3, 4, 5, 6, 7]
[]
[1, 2, 3, 4, 5, 6, 7]

Example 3:




# Python code to demonstrate the working of tee() 
    
# importing "itertools" for iterator operations 
import itertools
    
    
# using tee() to make a list of iterators 
  
for i in itertools.tee(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 4):
    # printing the values of iterators 
    print (list(i))


Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']

RELATED ARTICLES

Most Popular

Recent Comments