-1

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)

Marco Canora
  • 335
  • 2
  • 15
  • 6
    No, they can't; just use a regular `def`. – jonrsharpe Apr 09 '16 at 18:57
  • 1
    The main purpose of `lambda` function is that it can be define in-line. If you want to use a multi line function you can simply use regular functions with `def`. – Mazdak Apr 09 '16 at 19:01
  • The key word here is lambda *expression*; it cannot contain any statement, let alone more than one. – chepner Apr 09 '16 at 19:07

3 Answers3

3

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.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
1

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]
B. M.
  • 18,243
  • 2
  • 35
  • 54
1

For an interesting example of how far you can take lambda expressions check this out.

Although you should absolutely use a function for this.

Community
  • 1
  • 1
Pythonista
  • 11,377
  • 2
  • 31
  • 50