1

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.

3
  • 3
    print() is not a function in Python 2 unless you add from __future__ import print_function to the top of your script. Why are you trying to use it as a function? Commented Jul 25, 2015 at 18:55
  • @MartijnPieters The tutorial I was referring to was using the same. When I tried to mimic it, I got an error. I tried the same without the brackets like we normally do in python 2.7 but that failed too. Commented Jul 25, 2015 at 20:18
  • Your tutorial appears to be for Python 3; either switch tutorials or install Python 3, you'll have other problems. Commented Jul 25, 2015 at 22:24

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to use lambda x: print(x) then 1+1 inside a lamda, where the then represents something that just drops the None type and returns the right expression?
@CMCDragonkai I honestly can't think of a reason why you might want to do this, but since print (the function) returns None, you can use the or operator: lambda x: print(x) or other_value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.