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:
Function | This is the name of the function without parenthesis. |
Iterable | Any sequence like list, tuple, etc. |
Return value:
The reduce() function returns a single value as the output.
Example:
def multiply_numbers(m,n):
return m*n
from functools import reduce
numbers = [1,2,3,4,5]
output = reduce(multiply_numbers,numbers)
print(output)
Reduce with Lambda
The reduce function can be used with the lambda function. The lambda will receive and process the arguments.
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)
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.
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)