# [Tutor] Lambda

Kirby Urner urnerk@qwest.net
Mon, 04 Feb 2002 23:14:25 -0800

```Ditto the previous examples.

Plus:  here's without lambda -- yer basic function:

>>> def concat(a,b):  return a + b

>>> concat('A','C')
'AC'

And here's with, though in a way you wouldn't normally
see it:

>>> concat = lambda a,b: a+b
>>> concat('A','C')
'AC'

This just shows that lambda is setting up the basic
elements of a function:  parameters, what to do with
them.  It can't be very fancy because Python's lambdas
can't go on for lotsa lines -- just a way to do quicky
stuff.

So why use 'em?  Well, if you want to do some quickie
thing, it can seem a waste to go to all the trouble
to define a function, give it a name, the whole nine
yards.  All you really want is to do the thing, then
throw it away.  No need to memorialize the thing with
a name.  To borrow a slogan, a lambda means "Just Do It".

So the typical thing is to use it wherever you could
use a function.  Take the original concat:

def concat(a,b):  return a + b

Now I distribute it over some parameters.  concat wants
two parameters, and what map(function,list1,list2) will
do is grab one parameter from each of the following lists
-- so they'd better have the same number of elements:

>>> map(concat,['c','b','f'],['at']*3)
['cat', 'bat', 'fat']

But if I didn't want to bother with naming concat ahead
of time, I could do all of the above using a lambda,
making the function part of map(function,list1,list2)
contain an "anonymous function":

>>> map(lambda a,b: a+b, ['c','b','f'],['at']*3)
['cat', 'bat', 'fat']

A variation on the theme:

>>> apply(lambda a,b: a+b, ('c','at'))
'cat'

And now, for something completely silly:

>>> map(lambda z: apply(lambda a,b: a+b, z),zip(['f','c'],['at','at']))
['fat', 'cat']

Kirby

```