reduce

From CS 61A Wiki
Jump to: navigation, search

reduce is a higher-order function that is either built-in in Python 2 or can be imported from functools in Python 3.

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.

Form

The most general form of the reduce function is:

reduce(func, iter)

where func is the 2-argument function and iter is the iterable being processed.

Examples

Sum

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]

Applying reduce:

>>> 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).

Sources