← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 7 of 15

Python reduce()

What is reduce()?

reduce(function, iterable) folds a sequence down to a single accumulated value by repeatedly applying a two-argument function to a running total and the next element, left to right. Unlike map() and filter(), it isn't a built-in -- it must be imported from the functools module.

Example: What is reduce()?

python
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda acc, x: acc + x, numbers)
print(total)

Summing Lists with reduce()

Summing a list with reduce(lambda acc, x: acc + x, numbers) demonstrates the pattern clearly: the accumulator starts as the first element, and each step adds the next number to it, ending with the total -- though Python's built-in sum() does the exact same thing more directly for this specific case.

Example: Summing Lists with reduce()

python
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda acc, x: acc + x, numbers)
print(total)
print(sum(numbers))

Finding the Maximum

The same accumulator pattern finds a maximum or minimum by comparing the running accumulator against each next element and keeping whichever is larger (or smaller), which is essentially how reduce() generalizes any pairwise comparison into a single sequence-wide result.

Example: Finding the Maximum

python
from functools import reduce
numbers = [3, 7, 2, 9, 4]
maximum = reduce(lambda acc, x: x if x > acc else acc, numbers)
print(maximum)

Concatenating Strings with reduce()

reduce() isn't limited to numbers -- passing a string-concatenation lambda folds a list of strings into one combined string, showing that the accumulator pattern works for any type that supports the combining operation you provide.

Example: Concatenating Strings with reduce()

python
from functools import reduce
words = ["Hello", " ", "World"]
sentence = reduce(lambda acc, w: acc + w, words)
print(sentence)

Using Initializer Values

Passing a third argument to reduce() sets an explicit initial value for the accumulator instead of using the sequence's first element. This matters both for correctness with an empty sequence (which would otherwise raise TypeError) and for cases where you want the fold to start from a specific baseline value.

Example: Using Initializer Values

python
from functools import reduce
numbers = []
total = reduce(lambda acc, x: acc + x, numbers, 0)
print(total)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.