LAMBDA IS IT USELESS?

Tomasz Lisowski lisowski.tomasz at sssa.NOSPAM.com.pl
Thu Jul 12 09:43:02 CEST 2001


U¿ytkownik "EricIDLE" <grayson-wilson at home.com> napisa³ w wiadomo¶ci
news:tO837.679712$166.14009323 at news1.rdc1.bc.home.com...
> 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.
>
> 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??
>
> Or do I not get lambda?
>
> *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.

I am not sure about performance, but there are at least these advantages of
lambda:
1. They are easier to write (single line, no def or return statements)
2. They do not enter into your namespace (__dict__ dictionary), since thery
are not named
3. Without them, writing Tkinter callbacks would be horrible.

Following this thread I would give you a riddle to solve:
Code 1:
res = reduce(lambda x, y: x*y, some_list)

Code 2:
res = 1.0
for x in some_list: res *= x

Code 1 uses a builtin reduce function (fast), but nevertheless lambda
function gets called for each element in some_list.
Code 2 uses slower, native Python loop, but does not use any function calls

Question: which version is better from performance point of view?

Regards,
Tomasz Lisowski





More information about the Python-list mailing list