a=[ lambda t: t**n for n in range(4) ]

Terry Hancock hancock at anansispaceworks.com
Mon Apr 25 21:37:20 EDT 2005


On Saturday 23 April 2005 02:43 am, Mage wrote:
> Scott David Daniels wrote:
> > See, the body of your anonymous function just looks for "the current
> > value of n" when it is _invoked_, not when it is _defined_.
> 
> The "lambda functions" was an unclear part of the tutorial I read.
> Should I use them? Are they pythonic?
> As far I see they are good only for type less a bit.

Lambda has two main uses, IMHO:

1) You need to create a whole lot of functions which all follow a certain
pattern, but must evaluate "late" (i.e. the arguments will be added later,
so you can't just compute the result instead). This is basically the 
case the OP presented with his list of increasing powers.  You can, of
course, use named functions for each, but it may become impractical.

2) You are going to apply the same (arbitrary) function to many sets of arguments.
This argues for taking a function as an argument.  Python Imaging Library
does this with the 'point' method, for example.

Frequently you will run into a trivial case such as:

def squared_plus_one(x):
     return x**2 + 1

result_ob = source_ob(transform=squared_plus_one)

or something like that.  It gets pretty silly to clutter up your code with such
trivial functions, and lambda gives you a neat way to simply define the function
for the moment you need it and throw it away:

result_ob = source_ob(transform=lambda x: x**2 + 1)

Note that in this case, the expression is probably the clearest way to document
the function (clearer than the function name, IMHO).

So, yeah, they have some real uses.  But you can live without them most
of the time.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list