Aggregating with reduce()
reduce() combines all elements of a sequence into one value by repeatedly applying a function.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
It works like this: start with the first two elements, combine them, then combine the result with the third, and so on until one value remains.
The function takes two arguments: the accumulated result so far, and the next item.
You can provide a starting value:
# Start from 10 instead of the first element
total = reduce(lambda acc, x: acc + x, numbers, 10)
print(total) # 25
reduce() is powerful but can be hard to read. For common cases like sum or product, use built-in functions instead.
Master reduce in my Functional Programming course.