From CS 61A Wiki
Revision as of 09:57, 30 June 2014 by Axis (Talk | contribs)

Jump to: navigation, search

Reduce is a higher-order function that is either a built-in function in Python 2.7 or can be imported from functools in Python 3.2+.

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.

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, move on to the fourth element, and so on, until it reaches the end of the iterable. The final result will be the single return value.


The most general form of the reduce function is as follows:

reduce(func, iter)

with func being the 2-argument function given, and iter being the iterable being processed.



For the most basic example, we will attempt to add all elements of a list together. We'll create a starter function, add_together, and the list my_list below.

def add_together(x, y):
   return x+y
my_list = [1, 2, 3, 4, 5]

If we apply reduce to the above and apply them as arguments, we can expect:

>>>reduce(add_together, my_list)