TheChetan
TheChetan

Reputation: 4606

Error using the print function inside a lambda function in Python 2.7

I'm running a simple code in Python 2.7, but it is giving me syntax error.

hello = lambda first: print("Hello", first)

The error reported is SyntaxError: invalid syntax.

Upvotes: 1

Views: 1132

Answers (1)

vaultah
vaultah

Reputation: 46573

Python disallows the use of statements in lambda expressions:

Note that functions created with lambda expressions cannot contain statements or annotations.

print is a statement in Python 2, unless you import the print_function feature from __future__:

>>> lambda x: print(x)
  File "<stdin>", line 1
    lambda x: print(x)
                  ^
SyntaxError: invalid syntax
>>> from __future__ import print_function
>>> lambda x: print(x)
<function <lambda> at 0x7f2ed301d668>

Upvotes: 5

Related Questions