Python reduce() Function

The reduce() function takes a function and a sequence, and combines all the items into a single value. It works from left to right: it applies the function to the first two items, then applies it to that result and the third item, and so on.

reduce() lives in the functools module, so you must import it first.


Syntax

from functools import reduce

reduce(function, iterable, initial)

The initial value is optional. If given, it is used as the starting value before the first item.


Examples

Example 1: add all the numbers

from functools import reduce

def do_addition(x, y):
    return x + y

print(reduce(do_addition, [10, 20, 30, 40]))
Output of the above program is

100

Step by step it works like this: 10 + 20 = 30, then 30 + 30 = 60, then 60 + 40 = 100.

Example 2: multiply all the numbers

from functools import reduce

def do_multiplication(x, y):
    return x * y

print(reduce(do_multiplication, [10, 2, 3, 4]))
Output of the above program is

240

Example 3: with an initial value

from functools import reduce

print(reduce(lambda a, b: a + b, [1, 2, 3], 10))
Output of the above program is

16

The calculation starts from 10: 10 + 1 + 2 + 3 = 16.

Example 4: find the biggest number

from functools import reduce

print(reduce(lambda a, b: a if a > b else b, [4, 9, 2, 7]))
Output of the above program is

9

Note: For simple adding, multiplying or finding the maximum, the built-in sum(), max() and min() are shorter. Use reduce() when your combining rule is custom. Also, reduce() on an empty list without an initial value raises a TypeError.

Summary

  • reduce() combines a sequence into one value.
  • Import it with from functools import reduce.
  • You can give an initial value as the third argument.
  • Related: map() and filter().

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a lambda function in Python?
Why can’t a lambda function have statements in Python?