[Baypiggies] lambda for newbies

Shannon -jj Behrens jjinux at gmail.com
Fri May 11 10:03:44 CEST 2007


Hey guys,

I often hear Python newbies who are confused about lambda.  Let's
start with some code:

>>> def double(x):
...     return x * 2
...
>>> items = [1, 2, 9, 7]
>>> doubled = []
>>> for i in items:
...     doubled.append(double(i))
...
>>> print doubled
[2, 4, 18, 14]

These days, with list comprehensions, you can just write:

>>> doubled = [double(i) for i in items]
>>> doubled
[2, 4, 18, 14]

A more traditional lisp approach is to use the map function:

>>> doubled = map(double, items)
>>> doubled
[2, 4, 18, 14]

map applies a function (in this case, double) to the elements of an
iterable (in this case, the list items).

Notice we had to define the function above:

>>> def double(x):
...     return x * 2
...

For such a simple function, it'd be nice to just do it *in line* with
the actual code.  That's what lambda is for.  It's creates a little
*on the fly* function that doesn't even have a name:

>>> doubled = map(lambda x: x * 2, items)
>>> doubled
[2, 4, 18, 14]

In this case, lambda x: x * 2 is a function that takes x and returns x * 2.

Note that lambda is purposely very limited.  It's limited to a single
expression that's automatically the return value.  Things like print
statements aren't allowed because they don't have return values.  You
don't actually say return, because it's implied.

If your function is too complicated to fit in a lambda, write a
function (a def) and give it a name.  I think Guido made a conscious
decision to say, "Hey, if you're going to make a non-trivial function,
giving it a name makes it a lot more readable."

Happy Hacking!
-jj

-- 
http://jjinux.blogspot.com/


More information about the Baypiggies mailing list