Python reduce() Function


Python reduce() Function

The reduce() function will perform the rolling computation on the sequential pairs of the values.

It does not return the sequence of values, but it returns a single value as output.

This reduce() function is part of the functools module, so to use the reduce function, we have to import the functools module.

Syntax:

reduce(function, iterable)

Parameters:

FunctionThis is the name of the function without parenthesis.
IterableAny sequence like list, tuple, etc.

Return value:

The reduce() function returns a single value as the output.

Example:

In [1]:
def multiply_numbers(m,n):
    return m*n
In [2]:
from functools import reduce

numbers = [1,2,3,4,5]

output = reduce(multiply_numbers,numbers)

print(output)
120

Reduce with Lambda

The reduce function can be used with the lambda function. The lambda will receive and process the arguments.

In [1]:
from functools import reduce  

numbers = [1,2,3,4,5]

sum = reduce(lambda x, y: x+y, numbers)

print("Sum =",sum)

multiply = reduce(lambda x, y: x*y, numbers)

print("Multiplication =",multiply)
Sum = 15
Multiplication = 120

Reduce with Operator Functions

The reduce() function can be used with the operator functions instead of the lambda functions. This will make the code easier and precise. For this, we need to import the operator module.

In [1]:
from functools import reduce  
import operator 

numbers = [1,2,3,4,5]
my_list = ["I", "Love", "Python"]

sum = reduce(operator.add, numbers)

multiply = reduce(operator.mul, numbers)

my_string = reduce(operator.add, my_list)

print("Sum of numbers =", sum)

print("Multiply of numbers =", multiply)

print("Concatenation of the list =", my_string)
Sum of numbers = 15
Multiply of numbers = 120
Concatenation of the list = ILovePython

References

  1. Higher-order functions
  2. Python – Reduce Function