Reduce Function
reduce() is a function from the functools module that applies a function cumulatively to items in an iterable, reducing it to a single value. Syntax: from ...
What is reduce()?
reduce() is a function from the functools module that applies a function cumulatively to items in an iterable, reducing it to a single value. Syntax: from functools import reduce; reduce(function, iterable, initializer). Example: reduce(lambda acc, x: acc + x, [1, 2, 3, 4, 5]) computes ((((1+2)+3)+4)+5) = 15. reduce() was a built-in in Python 2 but was moved to functools in Python 3, reflecting Python's preference for explicit imports and for loops over functional idioms.
How reduce() Works Step by Step
reduce(f, [a, b, c, d]) is equivalent to f(f(f(a, b), c), d). The function f receives two arguments: the accumulated result so far and the next item. On the first call, it receives the first two items. On subsequent calls, it receives the accumulated result and the next item. This folding pattern is called a fold left in functional programming. The optional initializer argument is placed before the first item in the sequence.
Using an Initializer
The optional third argument to reduce() is an initializer, which serves as the starting value for the accumulator. reduce(lambda acc, x: acc + x, [1, 2, 3], 100) gives 106. The initializer also protects against errors with empty iterables: reduce(lambda a, b: a+b, []) raises TypeError, but reduce(lambda a, b: a+b, [], 0) returns 0. Always provide an initializer when the iterable might be empty.
Practical Uses of reduce()
reduce() is useful for computing running products: reduce(lambda a, b: a*b, [1,2,3,4,5]) gives 120 (5 factorial). It can flatten nested lists: reduce(lambda a, b: a+b, [[1,2],[3,4],[5,6]]) gives [1,2,3,4,5,6]. It can find the maximum without max(): reduce(lambda a, b: a if a>b else b, [3,1,4,1,5,9]). While Python provides built-in max(), min(), sum(), and other aggregators, reduce() covers custom aggregation logic that no built-in handles.
reduce() vs for Loop
Many uses of reduce() can be written more clearly as a for loop with an accumulator. result = 1; for x in nums: result *= x is arguably more readable than reduce(lambda a,b: a*b, nums, 1). Guido van Rossum himself expressed preference for explicit loops over reduce() for most use cases. Use reduce() when thinking in terms of fold operations or when the functional style genuinely improves readability, but do not force it where a loop is clearer.
Exam Tip
Exam questions about reduce() often ask: where is reduce() in Python 3? It is in the functools module (from functools import reduce). What does reduce(lambda a, b: a - b, [10, 2, 3]) return? It computes (10-2)-3 = 5 — always left-to-right. Another question: what happens if you call reduce() on an empty sequence with no initializer? TypeError is raised. Knowing the initializer's role in preventing that error is a detail that separates prepared students from unprepared ones.