LAMBDA IS IT USELESS?
paul at boddie.net
Thu Jul 12 12:59:36 CEST 2001
Greg Ewing <greg at cosc.canterbury.ac.nz> wrote in message news:<3B4D3CF1.889B57BB at cosc.canterbury.ac.nz>...
> EricIDLE wrote:
> > def mult(x,y):
> > return x * y
> > f = reduce(lambda x,y: x*y,n)
[mult is not needed if lambda is used]
> It's a matter of taste. Some people like the ability
> to write very trivial functions like your mult() in-line.
Amplifying the above explanation...
In this case, the use of lambda is convenient because * can't behave
like a function, so you need a quick way of wrapping * up to act like
The lambda construct lets you define a function "in-line" (as stated
above) without needing to call it something, or having it take up
space somewhere in your source file. The "mult" function could be seen
as "overkill" by some people in that such a standalone function isn't
likely to be widely useful and therefore doesn't justify its existence
as a standalone function.
In cases where you want to apply complicated expressions, the use of a
separate function becomes more compelling. Where control flow
constructs such as "if" are required, a separate function is
So, lambda is really only useful when you want to apply simple
expressions as if they were functions. Of course, a daring extension
to the Python language could let the following be written:
f = reduce(*, n)
f = reduce(*.as_function(), n)
But I'm not one to advocate this kind of thing. ;-) Besides, there are
still cases that this wouldn't address. For example:
f = reduce(lambda x, y: x + y/2, n)
More information about the Python-list