Why can’t a lambda function have statements in Python?
The body of a lambda must be one expression, because a lambda is only a short way to write a function that returns the value of that expression. Statements such as return, for, while, pass or an assignment are not expressions, so they are not allowed. Writing one gives a SyntaxError.
# This is NOT allowed
f = lambda x: return x * 2
You can still use an expression that makes a choice, like a conditional expression.
positive = lambda x: x if x > 0 else 0
print(positive(-5))
print(positive(8))
Output:
Tutorials Class - Output Window
0
8
If you need many lines, loops or several statements, write a normal function with def. Also read What is a lambda function?
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |