Muhammad Lukman Low
Muhammad Lukman Low

Reputation: 8533

Why this Python 2 lambda with print doesn't work?

Can someone explain to my why this very simple lambda expression does not work and what exactly is wrong?

 In [8]: print_me = lambda x: print x
  File "<ipython-input-8-269dab9ac1a1>", line 1
    print_me = lambda x: print x
                             ^
SyntaxError: invalid syntax

but

print_me = lambda x: x 

does ?

Upvotes: 3

Views: 80

Answers (1)

SmCaterpillar
SmCaterpillar

Reputation: 7020

In python 2.X print is a statement not a function. Accordingly, this is not supported by lambda functions. In python 3, however, lambda x: print(x) works since print is a function. You could also try to import the new print functionality in python 2.X:

from __future__ import print_function 
f = lambda x: print(x)
f(4)

which prints 4.

Upvotes: 4

Related Questions