Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python functools reduce() Function



The Python reduce() function reduces the multiple arguments into a single value. This function returns an aggregated value by applying it to an iterable. This starts with the first pair of arguments, then uses the result with the next value.

Syntax

Following is the syntax for the reduce() function.

reduce(func, iterable, initializer)

Parameters

The parameters for the partial() function are listed below −

  • func: This function takes two arguments and returns a single value.
  • iterable: This calculates the sequence of values that has to be reduced.
  • initializer: An initial value is used for accumulating the result. If the initial value is not specified, then the first element will serve as the initial value.

Return Value

This function returns a single aggregated value.

Example 1

In the example below, we are using reduce() function from the functools module this computes the sum and the maximum elements of a list by applying lambda functions to the list.

import functools
list = [5, 10, 15, 20, 25]
print("The sum of the list is : ", end="")
print(functools.reduce(lambda x, y: x+y, list))
print("The maximum elements are : ", end="")
print(functools.reduce(lambda x, y:   x if x > y else y, list))

Output

The result is generated as follows −

The sum of the list is : 75
The maximum elements are : 25

Example 2

In the following example we are using reduce() function to calculate the sum of a list.

from functools import reduce
def sum(x, y):
    return x+y
a = reduce(sum, [3, 5, 7, 9, 11])
print(a)

Output

The code is generated as follows −

35

Example 3

Now, we are calculating the initial value from the given arguments, and the lambda function adds two numbers at a time. The third parameter acts as the initial value in this process, which can be achieved using the reduce() function.

from functools import reduce
myNumbs = (2, 4, 6, 8, 10, 12, 14)
print(reduce(lambda x, y: x+y, myNumbs, 8))

Output

The output is obtained as follows −

64
python_modules.htm
Advertisements