← Go Back

reduce() Built-in Function

reduce() is a Python 2.x built-in function which takes a collection of values (a list, a tuple, or any iterable object) and "reduces" it to a single value. How that single value is obtained from the collection given as argument will depend on the function applied.

For example, the following code reduces the list [1, 2, 3, 4] to the number 10 by applying the add(a, b) function, which returns the sum of its arguments.

def add(a, b):
return a + b

print(reduce(add, [1, 2, 3, 4])) # 10

The function passed as the first argument must have two parameters. reduce() will be responsible for calling it cumulatively (that is, preserving the result of previous calls) from left to right. So the above code is equivalent to:

print(add(add(add(1, 2), 3), 4))

That is, the operation performed is ((1 + 2) + 3) + 4, which results in 10.

Starting with Python 3 the function was moved to the functools standard module, thus it must be imported:

from functools import reduce

built-ins functional-programming

🐍 You might also find interesting: