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.
SyntaxFollowing is the syntax for the reduce() function.
reduce(func, iterable, initializer)Parameters
The parameters for the partial() function are listed below −
This function returns a single aggregated value.
Example 1In 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 : 25Example 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 −
35Example 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4