Iterator Functions in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about the four iterator functions available in Python 3.x. Or earlier namely accumulate() , chain(), filter false() , dropwhile() methods.

Now let’s look on each of them in detail −

Accumulate () & chain() method

Accumulate() method takes two arguments, one being iterable to operate on and another the function/operation to be performed. By default, the second argument performs the addition operation.

Chain() method prints all the iterable targets after concatenating all of the iterables.

The below example explains the implementation −

Example

 Live Demo

import itertools
import operator as op
# initializing list 1
li1 = ['t','u','t','o','r']
# initializing list 2
li2 = [1,1,1,1,1]
# initializing list 3
li3 = ['i','a','l','s','p','o','i','n','t']
# using accumulate() add method
print ("The sum after each iteration is : ",end="")
print (list(itertools.accumulate(li1,op.add)))
# using accumulate() multiply method
print ("The product after each iteration is : ",end="")
print (list(itertools.accumulate(li2,op.mul)))
# using chain() method
print ("All values in mentioned chain are : ",end="")
print (list(itertools.chain(li1,li3)))

Output

The sum after each iteration is : ['t', 'tu', 'tut', 'tuto', 'tutor']
The product after each iteration is : [1, 1, 1, 1, 1]
All values in mentioned chain are : ['t', 'u', 't', 'o', 'r', 'i',
'a', 'l', 's', 'p', 'o', 'i', 'n', 't']

Dropwhile() & filterfalse() Method

Drop while() method accepts a function to check the condition and an input iterable to operate on. It returns all values of the iterable after the condition becomes false.

Filterfalse() method accepts a function to check the condition and an input iterable to operate on. It returns the value when the given condition becomes false.

Example

 Live Demo

import itertools
# list
l = ['t','u','t','o','r']
# using dropwhile() method
print ("The values after condition fails : ",end="")
print (list(itertools.dropwhile(lambda x : x!='o',l)))
# using filterfalse() method
print ("The values when condition fails : ",end="")
print (list(itertools.filterfalse(lambda x : x!='o',l)))

Output

The values after condition fails : ['o', 'r']
The values when condition fails : ['o']

Conclusion

In this article, we learned about the different types of iterator functions available in Python 3.x. Or earlier.

raja
Published on 29-Aug-2019 11:56:38
Advertisements