david4dev
david4dev

Reputation: 4914

Why can't print() be used in a lambda expression?

Why is:

p = lambda s: print(s)

invalid syntax but:

def do_print(s):
    print(s)
p = lambda s: do_print(s)

valid?

Upvotes: 6

Views: 1657

Answers (3)

user225312
user225312

Reputation: 131737

The body of a lambda has to be an expression, not a statement. print is a statement.

Update: As pointed out, in 2.x, print is a statement while in Python 3, it is a function.

Upvotes: 6

Dan D.
Dan D.

Reputation: 74655

which version of python are you using?; in python 2.7 (and before), print is a statement while in python 3 it's a function

Upvotes: 5

kingman
kingman

Reputation: 51

its the way the language is read it can't do p = lambda s: print(s) all in one step

Upvotes: -1

Related Questions