LAMBDA IS IT USELESS?

Alex Martelli aleaxit at yahoo.com
Thu Jul 12 04:35:18 EDT 2001


"EricIDLE" <grayson-wilson at home.com> wrote in message
news:tO837.679712$166.14009323 at news1.rdc1.bc.home.com...
> Ok well I dont quite grasp the Lambda concept heres an example.

Oh, the _concept_ is not too deep or complicated: lambda lets
you keep extremely-simple functions anonymous by defining them
'inline' where you use them (often, pass them as parameters).


> 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!?!?

Easier than what?


> But comon sense tells me this is easier.
>
> def mult(x,y):
>     return x * y
> f = reduce(mult,n)
> print f
>
> Isnt that easier??

Even 'easier' (and surely faster) would IMHO be:

import operator
f = reduce(operator.mul, n)
print f

Many 'appropriate' examples of lambda are things that module
operator exposes in a faster and more usable way.  When you
go beyond that, things can easily get too complicated for a
lambda to be well-readable.  There ARE a few exceptions, but
personally I'd rather have operator extended a little bit,
and/or use some form of currying.  So I hardly ever use
lambda, personally, nor do I suggest it to newbies.


> 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.

People do like to keep things anonymous, and sometimes they
have a point.  A well-chosen name can help make code clearer,
but if you care nothing about the name you're quite apt to
choose one that will instead make code LESS readable.  And
naming something often means 'breaking up' an expression into
a few statements -- that may well be beneficial to clarity
when the expression is overly complicated, but for some
expressions of middling complexity the breaking-up may
instead diminish readability by spreading things out too much.

I think you do "get lambda": it's nothing but a way to keep
some extremely simple functions anonymous and in-line.  I
tend to agree that, in Python as it exists today, lambda does
not add enough expressive power to "carry its weight" in
terms of added language complication (when teaching Python
to people without a background in other languages that include
some 'lambda' construct -- and such 'other languages' tend
to have fewer limitations on lambdas' power).  A slightly
richer module operator and a standardized way to curry any
arbitrary callable would be vastly preferable (it's easy to
cook up currying in Python today, but newbies having some
problems with lambda are unlikely to think of that:-).


Alex






More information about the Python-list mailing list