-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)

3
  • 6
    No, they can't; just use a regular def. Commented Apr 9, 2016 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. Commented Apr 9, 2016 at 19:01
  • The key word here is lambda expression; it cannot contain any statement, let alone more than one. Commented Apr 9, 2016 at 19:07

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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.

1 Comment

This outputs to standard output and returns [None].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.