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

2019-02-17 04:49发布

问题:

This does not work:

print((lambda :  return None)())

But this does:

print((lambda :  None)())

Why?

回答1:

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



回答2:

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.



回答3:

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:

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) 


标签: python lambda