Doctest failing

Chris Angelico rosuav at gmail.com
Mon Sep 12 03:03:24 CEST 2011


On Mon, Sep 12, 2011 at 4:43 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> Chris Angelico wrote:
>>
>> And I'd do this with a lambda, but that's just me. Of course, if your
>> logic is more complicated, it makes more sense to keep it in a named
>> function, but a single conditional call can fit nicely into a lambda.
>
> Lambdas are great when needed, but if don't *need* it, and you have more
> than a few, debugging can be a nightmare... "Okay, so this is function
> <lambda>... and that is function <lambda>... and over here we also have
> function <lambda>... ARGH!"

Yeah, they can be like the Bruces sketch at times.

A lambda is basically a function defined in an expression. For instance:

def add_one(x):
   return x+1

is (practically) the same as:

add_one = lambda x: x+1

In each case, you can call that function and will get back a value.
The advantage of lambdas is that, in a list comprehension or map call,
the code is right there instead of being elsewhere in a def statement.
But as you can see, they quickly become hard to read:

[j+2 for i in [[1,2,3],[4,5,6],[7,8,9]] for j in (lambda x: [q+10 for
q in x])(i)]

Their main advantage isn't in list comps, where you can already use
arbitrary expressions, but in calls that require a function as an
argument. The map() function is very similar to a generator
expression, but it can iterate over multiple iterables at once:

>>> list(map(lambda x,y: x+y,[1,2,3],[40,50,60]))
[41, 52, 63]

Note how the lambda keeps the code right there, whereas a def would
separate it out. It's obvious from this one expression that it's
adding successive corresponding pairs.

Hope that helps!

ChrisA



More information about the Python-list mailing list