Section 4: Functions as First Class Data

 Table of Contents > Chapter 5 > Section 4 

Functions in Python are first class data.  This means that you can treat them like any other data: they can be assigned as values to variables, they can be passed as arguments to other functions and they can be produced as values by other functions.

The following is a slightly simplified version of the documentation for Python's reduce function (http://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce).  Note that this is Python's equivalent of the abstract fold function that you saw in CPSC 110.
functools.reduce(function, sequence[, initializer])

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.  Suppose we define the following function:

def sub(a, b):
    """
    int, int -> int

    Produces the difference of a and b

    >>> sub(3, 4)
    -1
    """
    return a - b


Then the following call to reduce:

reduce(sub, [1, 2, 3, 4])

is the equivalent of sub(sub(sub(1, 2), 3), 4).

If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.  If initializer is not given and sequence contains only one item, the first item is returned.
It's important to note that the first argument passed to the reduce function is itself a function!

Just as you saw in CPSC 110, a lambda expression can be used to define an anonymous function.  Anonymous functions are best used when they are simple to define and are intended to be used only once.  The following anonymous function is equivalent to the sub function above:

>>> lambda a, b: a - b
However, we now have no way of actually calling this function - it doesn't have a name.  But we can do the following:

>>> fn = lambda a, b: a - b
>>> fn(6, 3)       #call the function and pass the arguments 6, 3
3
>>> fn(-8, 2)      #call the function and pass the arguments -8, 2
-10


We'll now consider an example where we pass an anonymous function as an argument to another function:

>>> reduce(lambda a, b: a + b, [1, 2, 3, 4])
10

This is equivalent to the following:

>>> fn = lambda a, b: a + b
>>> reduce(fn, [1, 2, 3, 4])
10                             # fn(fn(fn(1, 2), 3), 4)
                               # (((1 + 2) + 3) + 4)



Review 5.1

Question 1: determine the value produced by the following function call

reduce(lambda x, y: x * y, [3, 4, 5])

0
12
20
60
none of the above