Python reduce() Function
Description
reduce()The function accumulates the elements in the parameter sequence.
The function performs the following operations on all data in a data collection (list, tuple, etc.): it first uses the function passed to reduce (which has two parameters) to operate on the 1st and 2nd elements in the collection, then uses the function to operate the obtained result with the third data element, and finally obtains a result.
Note:In Python 3.x, reduce() has been moved to the functools module. If we want to use it, we need to import the functools module to call the reduce() function:
from functools import reduce
Syntax
The syntax of the reduce() function is as follows:
reduce(function, iterable[, initializer])
Parameters
- function -- A function with two parameters
- iterable -- An iterable object
- initializer -- Optional, initial parameter
Return Value
Returns the computed result of the function.
Examples
The following examples demonstrate the usage of reduce():
Example (Python 2.x)
# -*- coding: UTF-8 -*-
def add(x, y) : # Add two numbers
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # Calculate the list sum: 1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # Use lambda anonymous function
print(sum1)
print(sum2)
Example (Python 3.x)
from functools import reduce
def add(x, y) : # Add two numbers
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # Calculate the list sum: 1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # Use lambda anonymous function
print(sum1)
print(sum2)
The output of the above examples is:
15 15Other Extensions
Python Built-in Functions