Why can't I use “return” in lambda function in

2019-02-17 04:28发布

This does not work:

print((lambda :  return None)())

But this does:

print((lambda :  None)())

Why?

标签: python lambda
4条回答
霸刀☆藐视天下
2楼-- · 2019-02-17 04:42

Lambda can execute only statements and return result of the executed statement, result is the expression.

Consider using or and and operators to get more flexability in the values which will be returned by your lambda. See some samples below:

# return result of function f if bool(f(x)) == True otherwise return g(x)
lambda x: f(x) or g(x) 

# return result of function g if bool(f(x)) == True otherwise return False.
lambda x: f(x) or g(x) 
查看更多
乱世女痞
3楼-- · 2019-02-17 04:51

because lambda takes a number of parameters and an expression combining these parameters, and creates a small function that returns the value of the expression.

see: https://docs.python.org/2/howto/functional.html?highlight=lambda#small-functions-and-the-lambda-expression

查看更多
我只想做你的唯一
4楼-- · 2019-02-17 04:54

lambda functions automatically return an expression. They cannot contain statements. return None is a statement and therefore cannot work. None is an expression and therefore works.

查看更多
Lonely孤独者°
5楼-- · 2019-02-17 04:55

Because return is a statement. Lambdas can only contain expressions.

查看更多
登录 后发表回答