functools.reduce
Fold items into a single value by applying a function in turn.
Python 3.13
functools.reduce(function, iterable[, initial])Parameters
- functionCallable
- A function of two arguments: the accumulated value and the next item.
- iterableIterable
- The items to fold.
- initialAnyoptional
- The start value; with it, an empty iterable raises no error.
Return value
The final accumulated value.
Examples
Product of numbers
Python 3.13
from functools import reduce
print(reduce(lambda acc, x: acc * x, [1, 2, 3, 4]))24
Start value for an empty list
Python 3.13
from functools import reduce
print(reduce(lambda acc, x: acc + x, [], 0))0
Details
Raises TypeError for an empty iterable without initial. Common cases have ready-made functions, such as sum, math.prod, max, min and str.join, which are easier to read.
