Difference between revisions of "Reduce"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(copyedit; add explanation)
m (add_together: more precisely)
Line 26: Line 26:
Behind the scenes, <code>reduce</code> is actually computing <code>((((1 + 2) + 3) + 4) + 5)</code>.
Behind the scenes, <code>reduce</code> is actually computing <code>add(add(add(add(1, 2), 3), 4), 5)</code> or <code>((((1 + 2) + 3) + 4) + 5)</code>.
== Sources ==
== Sources ==
* https://docs.python.org/2/library/functions.html#reduce
* https://docs.python.org/2/library/functions.html#reduce
* https://docs.python.org/3.2/library/functools.html
* https://docs.python.org/3.2/library/functools.html

Revision as of 14:22, 4 July 2014

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