lambda with floats

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 9 00:31:56 EDT 2010


On Thu, 08 Apr 2010 21:32:10 -0400, monkeys paw wrote:

> I was going from example and looking for something useful from the
> lambda feature. I come from C -> Perl -> Python (recent). I don't find
> lambda very useful yet.

Perhaps you feel that lambda is a special kind of object. It isn't. It's 
just a short-cut for creating an anonymous function object.

f = lambda x: x+1 

is almost exactly the same as:

def function(x):
    return x+1

f = function
del function


The only advantages of lambda are:

(1) you can write a simple function as a one-liner; and
(2) it's an expression, so you can embed it in another expression:

list_of_functions = [math.sin, lambda x: 2*x-1, lambda x, y=1: x**y]
for func in list_of_functions:
    plot(func)


The disadvantage of lambda is that you can only include a single 
expression as the body of the function.

You will generally find lambdas used as callback functions, and almost 
nowhere else.


-- 
Steven



More information about the Python-list mailing list