What does functools.reduce's initializer argument do, and why should you usually provide one?
Short answer
The optional third argument to reduce serves as the starting accumulator value and is returned as-is if the iterable is empty.
Advertisement
AModel answer
The optional third argument to reduce serves as the starting accumulator value and is returned as-is if the iterable is empty. Without it, reduce raises TypeError on an empty iterable and uses the first element as the initial accumulator, which can produce subtly wrong results for operations that aren't naturally idempotent.
from functools import reduce
# Without initializer: fails on empty list
try:
reduce(lambda a,b: a+b, [])
except TypeError as e:
print('Error:', e)
# With initializer: safe
print(reduce(lambda a,b: a+b, [], 0)) # 0Real-world example
An analytics pipeline reducing a possibly-empty list of daily sales always passes 0 as the initializer to avoid crashing on days with no data.
Likely follow-ups
- What's the type of the initializer relative to the sequence elements?
- How does reduce compare to itertools.accumulate?
Related topics