lambda functions

Functions are objects (like everything else in Python) and so can be stored in lists. Without using lambda we would have to define named functions (using def) before constructing the list:

def const(x):
    return 1.
def lin(x):
    return x
def square(x):
    return x**2
def cube(x):
    return x**3
flist = [const, lin, square, cube]

Then flist[3](5) returns 125, since flist[3] is the function cube, and is called with the argument 5.

The value of using lambda expressions as anonymous functions is that if these functions do not need to be named if they are just to be stored in a list and so can be defined as items "inlin" with the list construction:

>>> flist = [lambda x: 1,
...          lambda x: x,
...          lambda x: x**2,
...          lambda x: x**3]
>>> flist[3](5)   # flist[3] is x**3
125
>>> flist[2](4)   # flist[2] is x**2
16