Python reduce() function

Updated on Nov 09, 2019


The reduce() function accepts a function and a sequence and returns a single value calculated as follows:

  1. Initially, the function is called with the first two items from the sequence and the result is returned.
  2. The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps repeating until there are items in the sequence.

The syntax of the reduce() function is as follows:

Syntax: reduce(function, sequence[, initial]) -> value

When the initial value is provided, the function is called with the initial value and the first item from the sequence.

In Python 2, reduce() was a built-in function. However, in Python 3, it is moved to functools  module. Therefore to use it, you have to first import it as follows:

from functools import reduce # only in Python 3

Here is an example which adds all the items in the list.

1
2
3
4
5
6
7
8
9
>>>
>>> from functools import reduce
>>> 
>>> def do_sum(x1, x2): return x1 + x2
... 
>>> 
>>> reduce(do_sum, [1, 2, 3, 4])
10
>>>

Try it out:

from functools import reduce
 
def do_sum(x1, x2): 
    return x1 + x2

print(reduce(do_sum, [1, 2, 3, 4]))

This reduce() call perform the following operation:

(((1 + 2) + 3) + 4) => 10

The preceding reduce() call is functionally equivalent to the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> 
>>> def my_reduce(func, seq):
...     first = seq[0]
...     for i in seq[1:]:
...         first = func(first, i)
...     return first
... 
>>> 
>>> my_reduce(do_sum, [1, 2, 3, 4])
10
>>>

Try it out:

def do_sum(x1, x2): 
    return x1 + x2

def my_reduce(func, seq):
    first = seq[0]
    for i in seq[1:]:
        first = func(first, i)
    return first

print(my_reduce(do_sum, [1, 2, 3, 4]))

However, the reduce() call is much more concise and performs significantly better than the for loop.


Other Tutorials (Sponsors)