reduce()





Hello folks....!!!!
Today we are going to work with the reduce() function.

reduce() function 

    It is also a function like map() and filter(). It takes up two arguments - a function and iterables, but it does not return an iterable. It returns a single value. That is why it got its name. The syntax is :

reduce(function,iterable)

Initially it was a built-in function. But in Python 3, it was moved to functools package. So it is necessary to import that function from the package to avoid errors. To import it, in the beginning of the code snippet write :
from functools import reduce

Whichever package you are using, you have to follow the same syntax as given above. 

Let us understand this function via simple examples.

Example 1: user defined function and integer elements

Calculate the product of a list :

product of a list

How each iteration works ?

iteration 1 : x=1, y=3 --- x=1*3=3
iteration 2 : x=3, y=6 ---x=18
iteration 3 : x=18, y=4 ---x=72
iteration 4 : x=72, y=10 ---x=720
ans=720

Example 2 : lambda functions and string elements

demonstrate .join() function using reduce :

reduce() in python

The Example 1 can be more effectively implemented using the operator module. Look at the code snippet below:

Example 3: Calculate the product of the list using operator

reduce() in python

Many other functions are also available with the operators module which will be explained in upcoming chapters. For now you can use :
  • operators.add
  • operators.sub
  • operators.mul
  • operators.truediv
  • operators.floordiv

Example 4: Using conditions 

Demonstrate max() and min() of the list using reduce.

reduce() in python

Let us display the internal working of the above example :
For display purpose, I have coded the function for finding maximum element. In the similar way minimum element is also found out. Look at the code below:

reduce() in python



Next Topic👉

Comments