functools.reduce
Fold items into a single value by applying a function in turn.
Python 3.13
functools.reduce(function, iterable[, initial])- [ ]optional part
- function
- A function of two arguments: the accumulated value and the next item.Callable
- iterable
- The items to fold.Iterable
- initial
- The start value; with it, an empty iterable raises no error.AnyOptional
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.
