Can lambda expression has multiple lines in Python? Like common functions.
Can I do something like that?
res = lambda x y:
z = x**2 + 5
z + x + y
(I know that this function can be written on one line, It's an example)
Can lambda expression has multiple lines in Python? Like common functions.
Can I do something like that?
res = lambda x y:
z = x**2 + 5
z + x + y
(I know that this function can be written on one line, It's an example)
They can be split across multiple lines by the same rule that any expression can be split across multiple lines. You can use backslash \
to prevent a linebreak ending the current statement, or use the fact that linebreaks are permitted within the various forms of brackets: ()
, []
, {}
.
However, a lambda expression is just that, an expression. It cannot contain assignment statements (or any other statements).
The precise details are defined by the Python grammar.
IMHO , you can't.
If you need some temporary variable in a lambda function, as a ugly workaround you can do :
res = lambda x,y : [ z**2 + z**4 + z for z in [x**2+5]][0]
For an interesting example of how far you can take lambda expressions check this out.
Although you should absolutely use a function for this.