Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools reduce() Function



The Pythonreduce() 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 thereduce() function.

reduce(func, iterable, initializer)

Parameters

The parameters for thepartial() 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 usingreduce() function from the functools module this computes the sum and the maximum elements of a list by applying lambda functions to the list.

import functoolslist = [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 : 75The maximum elements are : 25

Example 2

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

from functools import reducedef sum(x, y):    return x+ya = 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 thereduce() function.

from functools import reducemyNumbs = (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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp