Python reduce() Function
Description
reduce() The function accumulates the elements of a sequence.
The function performs the following operation on all data in a collection (list, tuple, etc.): the function function passed to reduce (with two arguments) is first applied to the 1st and 2nd elements of the collection, the result is then combined with the third element using function, and so on, finally producing a single result.
Note:In Python 3.x, reduce() has been moved to the functools module. To use it, you need to import the functools module to call the reduce() function:
from functools import reduce
Syntax
reduce() function syntax:
reduce(function, iterable[, initializer])
Parameters
- function -- a function with two arguments
- iterable -- an iterable object
- initializer -- optional, the initial value
Return Value
Returns the result of the function computation.
Example
The following examples demonstrate how to use reduce():
Example (Python 2.x)
#!/usr/bin/python
-- coding: UTF-8 --
def
add
(
x
,
y
)
:
add two numbers
return
x + y
sum1
=
reduce
(
add
,
[
1
,
2
,
3
,
4
,
5
]
)
Calculate the sum of the list: 1+2+3+4+5
sum2
=
reduce
(
lambda
x
,
y: x+y
,
[
1
,
2
,
3
,
4
,
5
]
)
Use a lambda anonymous function
(
sum1
)
(
sum2
)
Example (Python 3.x)
#!/usr/bin/python
from
functools
import
reduce
def
add
(
x
,
y
)
:
add two numbers
return
x + y
sum1
=
reduce
(
add
,
[
1
,
2
,
3
,
4
,
5
]
)
Calculate the sum of the list: 1+2+3+4+5
sum2
=
reduce
(
lambda
x
,
y: x+y
,
[
1
,
2
,
3
,
4
,
5
]
)
Use a lambda anonymous function
(
sum1
)
(
sum2
)
The output of the above example is:
15
15
Python built-in function