Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 302
Muhammad Lukman Low Avatar asked Feb 18 '26 03:02

Muhammad Lukman Low


1 Answers

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.

like image 108
SmCaterpillar Avatar answered Feb 20 '26 17:02

SmCaterpillar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!