Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a lambda function in single line using semicolons in python 3

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)

like image 986
ozgeneral Avatar asked Sep 19 '25 21:09

ozgeneral


1 Answers

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.

like image 129
Kevin Avatar answered Sep 22 '25 12:09

Kevin