Given a two-argument function, an iterable, and optionally an initalizer,
reduce applies the function to each item pair in the sequence cumulatively and returns a single value. More precisely,
reduce will take the first two elements of the iterable, apply the function to them, and reach a result. It will then apply the function to this result and the third element, apply the function to the result of that and the fourth element, and so on, until it reaches the end of the iterable. The return value will be the final result.
The most general form of the
reduce function is:
func is the 2-argument function and
iter is the iterable being processed.
We can use
reduce to sum all elements of a list. We define the following:
def add(x, y): return x + y lst = [1, 2, 3, 4, 5]
>>> reduce(add, lst) 15
Behind the scenes,
reduce is actually computing
add(add(add(add(1, 2), 3), 4), 5) or
((((1 + 2) + 3) + 4) + 5).