functools.reduce in Python

In Python, the reduce is a function of the functools module. This function will return a single value result by solving a sequence on a two-argument function. In other words, this is useful particularly when we want to reduce the set of values to a single one.

Syntax

The signature for the reduce function is as shown below. Here, in presence of the optional initializer, it will serve as a default in the calculation when an iterable is empty. However, if the initializer is not given and iterable contains only one item, it will return the first item.

reduce(func,iterable, initializer)

Python functools.reduce Example:

Example 1: In this case, we are computing the summation of a numbers in the list using the built-in add module of an operator.

from functools import reduce
from operator import add

l = [112, 211, 135, 524, 655]

#Using reduce method and printing
result = reduce(add, l)
print("Sum of numbers in list is ",result)

Output

Sum of numbers in list is 1637

Example 2: In this case, we are computing the multiplication of a numbers in the list.

from functools import reduce

# Function computing multiplication 
def product(num1,num2):
    res=num1*num2
    print("Computing ",num1," * ",num2," = ",res)
    return res

#Computing the product of numbers in the list 
product = reduce(product,[1,2,3,4,5])
print("Final answer is ",product)

Output

Computing  1  *  2  =  2
Computing  2  *  3  =  6
Computing  6  *  4  =  24
Computing  24  *  5  =  120
Final answer is  120

Example 3: In this case, we are concatenating the words in the tuple to form a single string.

from functools import reduce
 
def concate(string1, string2):
    return (string1+string2)

# Using tuple to get the words 
t = ("Life","is","a","book")

#Using reduce to concate the words in tuple
s = reduce(concate,t)
print("String is ",s)

Output

Lifeisabook

Conclusion

Hence, We can use the reduce method as an alternative to the iteration if we want to get the single value from an iterable.

References

Happy Learning 🙂

Leave A Comment