[Tutor] Why use lambda?

Danny Yoo dyoo at cs.wpi.edu
Sat Aug 2 18:26:00 CEST 2008


> What can lambda do that normal function definitions cannot?
> Is it quicker to execute/less memory intensive?
> Or is it just quicker to type and easier to think about?

Notational convenience.  Think about how, in arithmetic expressions,
how we're not forced to give explicit names to all the subexpressions:

#########################
def hypotenuse(a, b):
    return ((a * a) + (b * b))**0.5
#########################

Imagine a world where we have to give explicit names to all of the
subexpressions:

###################
def hypotenuse(a, b):
    tmp1 = a * a
    tmp2 = b * b
    tmp3 = tmp1 + tmp2
    tmp4 = tmp3**0.5
    return tmp4
####################

Does this look funny to you?  Why?



Sometimes we don't care what something is named: we just want to use
the value.  lambda's use is motivated by the same idea: sometimes, we
want to use a function value without having to give a name. Here's a
toy example.

####################################
def deepmap(f, datum):
    """Deeply applies f across the datum."""
    if type(datum) == list:
        return [deepmap(f, x) for x in datum]
    else:
        return f(datum)
####################################

If we wanted to apply a squaring on all the numbers in the nested list
(while still maintaining the nested structure):

    [42, 43, [44, [45]]]

then we can use deepmap by feeding in a square function to it.

##############################
def square(x):
    return x * x

deepmap(square, [42, 43, [44, [45]]])
###############################

An alternative way to express the above is:

    deepmap(lambda x: x *x, [42, 43, [44, [45]]])

Here, we avoid having to first give a name to the function value we're
passing to deepmap.


More information about the Tutor mailing list