Fix Python – Why doesn’t print work in a lambda?

Question

Asked By – Anycorn

Why doesn’t this work?

lambda: print "x"

Is this not a single statement, or is it something else?
The documentation seems a little sparse on what is allowed in a lambda…

Now we will see solution for issue: Why doesn’t print work in a lambda?


Answer

A lambda‘s body has to be a single expression. In Python 2.x, print is a statement. However, in Python 3, print is a function (and a function application is an expression, so it will work in a lambda). 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

This question is answered By – L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0