Python reduce()
In this page:
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()?
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()
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
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()
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
from functools import reduce
numbers = []
total = reduce(lambda acc, x: acc + x, numbers, 0)
print(total)
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects