LAMBDA IS IT USELESS?

Remco Gerlich scarblac at pino.selwerd.nl
Thu Jul 12 05:12:36 EDT 2001


EricIDLE <grayson-wilson at home.com> wrote in comp.lang.python:
> Ok well I dont quite grasp the Lambda concept heres an example.
> 
> def mult(x,y):
>     return x * y
> f = reduce(lambda x,y: x*y,n)
> print f
> 
> *NOTE   The varible N is defined in the code before this excerpt.

Note that the def mult is completely unused here.
 
> Anyways back to the point the book says this is easier!?!?
> 
> But comon sense tells me this is easier.
> 
> def mult(x,y):
>     return x * y
> f = reduce(mult,n)
> print f
> 
> Isnt that easier??

It's exactly the same to me, but the first is only one line (if you delete
the def).

I'd use operator.mul though, it's faster.

> Or do I not get lambda?

You do, every lambda can be trivially rewritten as a def, just not inside
an expression: you need to def the function before the expression.

> *NOTE ... I think its just a way to complicate things OR just a way to avoid
> typing the function name beacuse.... I dont know they are scared of the
> names they give them.

Using a def is a few more lines, it needs a name, and it puts a bit of space
between the definition of the function and the expression. But they're more
powerful.

Lambda is a minor convenience at most, of course, and a minor annoyance
according to some (among whom is Guido, iirc).

Nowadays I'd rather use a list comprehension than a map(lambda ....)
construction.

-- 
Remco Gerlich



More information about the Python-list mailing list