How to print lambda result ?

alex23 wuwei23 at gmail.com
Tue Jan 20 07:51:26 EST 2009


On Jan 20, 10:34 pm, "Barak, Ron" <Ron.Ba... at lsi.com> wrote:
> What I still don't understand is why the print does not
> execute the lambda and prints the result, instead of
> printing the lambda's object description.

The following two statements are identical:

>>> def f(x): return x
...
>>> f = lambda x: x

lambda _creates_ a function, it's up to you to actually _call_ the
function. Functions are first class objects in Python, so the tuple
you're passing in to the string format contains a number and a
function.

Tino's solutions are definitely more what you're looking for, but for
your lambda version to work, you have to actually call the lambda
function, passing in num when you do so (as you've specified that the
lambda function requires one argument):

>>> for num in range(1, 4):
...     string_ = "%d event%s" % (num, (lambda num: num > 1 and "s" or
"")(num))
...     print string_

Or you can remove the argument and create a closure using the num
value from the loop:

...     string_ = "%d event%s" % (num, (lambda: num > 1 and "s" or "")
())

But again, this is generally overkill when all you're after is a
conditional value.

Personally, I tend to use lambdas for passing small units of
functionality into other functions, or if I want to create a quick
closure. Your mileage may vary on what you consider a suitable use
case, but you will -still- have to call your lambda in order for it to
execute :)
Generally



More information about the Python-list mailing list