First one needs to understand that the lambda
construct creates an expression that evaluates to the created function. This is very different from a def
, which is a statement, and works by side effect of binding the created function to the specified name. For lambda
to be useful at all, it must be an expression, otherwise you couldn't nest it in other expressions.
As the linked FAQ explains, no other Python expression is allowed to nest statements. This is because the core syntactic tradeoffs of the Python language preclude such possibility, as persuasively argued by Guido. Since there is a very easy workaround, i.e. using a def
, it was deemed not worthwhile to warp the syntax of the language to accomodate statements in lambda
.
Also note that lambda
is not the only place in the language that requires an expression. You can't put a statement in the test of an if
or while
, nor in the expression required by the for
statement. Yet this is considered a good thing - if you need statements there, simply extract them into a function and call it. Exactly the same applies to lambda
.