From CS 61A Wiki
Revision as of 14:23, 4 July 2014 by Axis (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.


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.



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)

Behind the scenes, reduce is actually computing add(add(add(add(1, 2), 3), 4), 5) or ((((1 + 2) + 3) + 4) + 5).