Back to results for “Functional Programming”
Python › functools & Functional Programming Tools

What does functools.reduce do, and why is it often discouraged in favor of loops?

Intermediate

Answer

reduce(function, iterable, initializer) cumulatively applies a binary function to items of an iterable, reducing it to a single value. It's discouraged for complex logic because the accumulation is implicit and harder to read than an explicit loop or a built-in like sum() or math.prod(), which are clearer for common cases.
from functools import reduce

product = reduce(lambda acc, x: acc * x, [1,2,3,4], 1)
print(product)  # 24
Real-world example A financial report combines a list of transaction deltas into a running total balance using reduce, though sum() would be clearer for simple addition.

Common follow-ups: When is reduce clearer than a for-loop?;What's the role of the initializer argument?