In python3, following works:
print(3); print(5)
However following gives a syntax error due to semicolon:
(lambda key: (print(3); print(5)))
Why is that, and is there a way to write a lambda function in single line (I intend to pass it as a short argument, without defining the function elsewhere)
Existing answers cover the "how?" of the question, but not the "why". Which is to say, why doesn't lambda: print(3); print(5)
work? The answer is in the language specification.
From https://docs.python.org/3/reference/expressions.html#lambda:
Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression
lambda arguments: expression
yields a function object. [...] Note that functions created with lambda expressions cannot contain statements or annotations.
From https://docs.python.org/3/reference/simple_stmts.html?highlight=semicolon#simple-statements:
A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons.
print(3); print(5)
contains a semicolon, so it is a collection of simple statements. But a lambda can't contain statements. So a lambda can't contain print(3); print(5)
.
So why does (lambda key: (print(3), print(5)))
work? It's because (print(3), print(5))
is not a statement. It's an expression: in particular, it is a tuple literal (formally, a parenthesized form whose expression list contains at least one comma), whose first element is a call to print
with argument 3, and whose second element is a call to print
with argument 5. All of this is a single expression, so lambda accepts it without trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With