29

This does not work:

print((lambda :  return None)())

But this does:

print((lambda :  None)())

Why?

2
  • 1
    Why would you want to? Do you have a specific example we can help with? May 4, 2016 at 9:58
  • I m trying to give an educational example of the most simplistic lambda function - empty lambda
    – ERJAN
    May 4, 2016 at 9:59

5 Answers 5

36

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

1
  • 2
    great, also insightful into the nature of lambdas - they can only contain expressions
    – ERJAN
    May 4, 2016 at 10:01
12

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.

10

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

Consider using or and and operators to short-circuit the result for more flexibility 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 f(x).
lambda x: f(x) and g(x) 
4

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

0

Remember a lambda can call another function which can in turn return anything (Even another lambda)

# Does what you are asking... but not very useful
return_none_lambda = lambda : return_none()
def return_none():
    return None

# A more useful example that can return other lambdas to create multipier   functions
multiply_by = lambda x : create_multiplier_lambda(x)
def create_multiplier_lambda(x):
    return lambda y : x * y

a = multiply_by(4)
b = multiply_by(29)

print(a(2)) # prints 8
print(b(2)) # prints 58
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.