Why doesn't this work?
lambda: print "x"
Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
Why doesn't this work?
lambda: print "x"
Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
A lambda
's body has to be a single expression. In Python 2.x, print
is a statement. However, in Python 3, print
is a function (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the latest Python 2.x:
In [1324]: from __future__ import print_function
In [1325]: f = lambda x: print(x)
In [1326]: f("HI")
HI
The body of a lambda has to be an expression that returns a value. print
, being a statement, doesn't return anything, not even None
. Similarly, you can't assign the result of print
to a variable:
>>> x = print "hello"
File "<stdin>", line 1
x = print "hello"
^
SyntaxError: invalid syntax
You also can't put a variable assignment in a lambda, since assignments are statements:
>>> lambda y: (x = y)
File "<stdin>", line 1
lambda y: (x = y)
^
SyntaxError: invalid syntax
With Python 3.x, print CAN work in a lambda, without changing the semantics of the lambda.
Used in a special way this is very handy for debugging. I post this 'late answer', because it's a practical trick that I often use.
Suppose your 'uninstrumented' lambda is:
lambda: 4
Then your 'instrumented' lambda is:
lambda: (print (3), 4) [1]