[Tutor] Lambda

Sean 'Shaleh' Perry shalehperry@attbi.com
Mon, 04 Feb 2002 23:04:34 -0800 (PST)


> 
> I not only find them counterintuitive, but can't even figure out what they do
> in a line of code.  I would be grateful if someone could translate a line
> using lambda into one that doesn't.  
> 

Let's use an easy example.

>>> f = lambda x,y: max(x,y)
>>> f(2,4)
4

lambda simply declares a function, like def does.  The difference being that
lambdas may only contain expressions, so 'print' is not allowed.

The above code assigns the function that lambda creates to f and we then use f
to call the function.

lambdas are really useful for callbacks in GUI programming.  Often in C++ I
find myself defining a function just so it can be called by an event.  As other
posters will no doubt show, they are also handy for map, filter, reduce and
friends.

>>> l = [1,2,3,4,5,6,7,8]
>>> reduce(f, l) 
8

Uses the lambda I created above.  reduce() passes the first two elements of the
list to the function, keeps the return value and passes in the next element of
the list.  Often you see people sum lists with it.  This is another interesting
use.

def reduce(func, container):
    holder = container[0]
    for i in container[1:]:
        holder = func(holder, i)
    return holder

is a possible implementation of the reduce() function from python.  That 'func'
operator would have to be delcared elsewhere, maybe only to be used one time.