tags:

views:

98

answers:

5

hello.

How come this is not allowed?

lambda: print "x"

is this not a single statement or something else? documentation is a little sparse on what allowed lambda is

thank you

+6  A: 

what you've written is equivalent to

def anon():
    return print "x"

which also results in a SyntaxError, python doesn't let you assign a value to print in 2.xx; in python3 you could say

lambda: print('hi')

and it would work because they've changed print to be a function instead of a statement.

dagoof
There's also `from __future__ import print_function`, which enables this in py2.x
tzaman
Or alternatively `lambda: sys.stdout.write('hi')`
fmark
+1  A: 

The body of a lambda has to be a single expression. print is a statement, so it's out, unfortunately.

tzaman
thank you, I was not sure about definition of expression versus statement, now it makes sense
aaa
+3  A: 

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
Paul Kuliniewicz
+7  A: 

A lambda is a single expression. In Python 2.x, print is a statement. However, in Python 3, print is a function. 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
Longpoke
+2  A: 

Here, you see an answer for your question. print is not expression in Python, it says.

vpit3833
Incomplete answer, but nice link.
Stephen