Python reduce()
In this page:
from functools import reduce
reduce(function, iterable, initial_value)
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) # folds the list into one accumulated value
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) # accumulator pattern
print(total)
print(sum(numbers)) # built-in sum() does the same thing more directly
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) # keeps the larger of acc and x each step
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) # accumulator pattern works for strings too
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) # explicit initial value, avoids TypeError on an empty list
print(total)
- Forgetting the import, as in
reduce(...)withoutfrom functools import reduce, which raisesNameErrorin Python 3. - Calling
reduceon an empty list without an initial value, which raisesTypeError. - Using a function that takes the wrong number of arguments; the reducing function must accept exactly two.
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