Python - Reduce Function

The reduce() function is defined in the functools module. Like the map and filter functions, the reduce() function receives two arguments, a function and an iterable. However, it doesn't return another iterable, instead it returns a single value.

Syntax:

functools.reduce(myfunction, iterable, initializer)

The argument function is applied cumulatively to arguments in the list from left to right. The result of the function in the first call becomes the first argument and the third item in list becomes second. This is repeated until the list is exhausted.

In the example below, the mult() function is defined to return the product of two numbers. This function is used in the reduce() function along with a range of numbers between 1 and 4, which are 1,2 and 3. The output is a factorial value of 3.

Example: reduce()
import functools
def mult(x,y):
    print("x=",x," y=",y)
    return x*y

fact=functools.reduce(mult, range(1, 4))
print ('Factorial of 3: ', fact)
Result:
X=1 y=2
X=2 y=3
Factorial of 3: 6