Use def instead.

def d(x):
    if x:
        return 1
    else:
        return 2

All python functions are first order objects (they can be assigned to variables and passed around as arguments), lambda is just a convenient way to make short ones. In general, you are better off using a normal function definition if it becomes anything beyond one line of simple code.

Even then, in fact, if you are assigning it to a name, I would always use def over lambda (something PEP 8 explicitly recommends as it improves debugging). lambda is really only a good idea when defining short functions that can be placed inline into the function call, for example key functions for use with sorted().

Note that, in your case, a ternary operator would do the job (lambda x: 1 if x else 2), but I'm presuming this is a simplified case and you are talking about cases where it's not reasonable to use a single expression.

(As a code golf note, this could also be done in less code as lambda x: 2-bool(x) - of course, that's highly unreadable and a bad idea.)

Answer from Gareth Latty on Stack Overflow
Discussions

Why doesn't Python allow multi-line lambdas? - Software Engineering Stack Exchange
Can someone explain the concrete reasons why BDFL choose to make Python lambdas single line? This is good: lambda x: x**x This results in an error: lambda x: x**x I understand that making la... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
syntax - How can multiline lambdas be designed in indent based languages? - Programming Language Design and Implementation Stack Exchange
This is all enough for lambda functions ... then it can span multiple lines. (Of course, this applies to every expression, not just lambdas.) Lambda functions whose body is a block of statements, on the other hand, are considerably more difficult. Python's solution is to just not ... More on langdev.stackexchange.com
🌐 langdev.stackexchange.com
June 5, 2023
syntax - No Multiline Lambda in Python: Why not? - Stack Overflow
This is a simple ambiguity that ... on multiple lines). Multi-line lambdas would not be especially different from these cases that it warrants excluding them on that basis. This is the real answer. 2014-03-07T13:41:04.677Z+00:00 ... I like how there are gazillion languages that deal with it no fret, but somehow there are some deep reasons why it's supposedly very hard if not impossible 2019-11-18T16:07:07.753Z+00:00 ... For functional programming, I'd go with Scala over Python any ... More on stackoverflow.com
🌐 stackoverflow.com
Returning a multi-line lambda function inside an outer function
You do not need a lambda function. By definition, lambdas are small one-line functions with no statements. If you need more than that, you need a normal function definition. Note that the object produced by a lambda is exactly the same as the object produced by a standard function definition. There is nothing that a lambda can do that a standard function cannot. More on reddit.com
🌐 r/learnpython
11
6
May 26, 2022
🌐
Python.org
discuss.python.org › ideas
Simple multi-line lambda syntax - Ideas - Discussions on Python.org
June 7, 2023 - Supports type hints and does not break python semantics afaik app.watch('message', lambda (message: str, origin: str) -> bool: ( # multi-line code here ))
🌐
Python
wiki.python.org › moin › MultiLineLambda
MultiLineLambda - Python Wiki
February 6, 2024 - With an inline multi-line lambda, you probably need a comment summarizing what the function is doing.
Top answer
1 of 5
52

Guido van van Rossum answered it himself:

But such solutions often lack "Pythonicity" -- that elusive trait of a good Python feature. It's impossible to express Pythonicity as a hard constraint. Even the Zen of Python doesn't translate into a simple test of Pythonicity...

In the example above, it's easy to find the Achilles heel of the proposed solution: the double colon, while indeed syntactically unambiguous (one of the "puzzle constraints"), is completely arbitrary and doesn't resemble anything else in Python...

But I'm rejecting that too, because in the end (and this is where I admit to unintentionally misleading the submitter) I find any solution unacceptable that embeds an indentation-based block in the middle of an expression. Since I find alternative syntax for statement grouping (e.g. braces or begin/end keywords) equally unacceptable, this pretty much makes a multi-line lambda an unsolvable puzzle.

http://www.artima.com/weblogs/viewpost.jsp?thread=147358

Basically, he says that although a solution is possible, it's not congruent with how Python is.

2 of 5
30

it's perfectly fine to do a multi line lambda in python: see

>>> f = lambda x: (
...   x**x)
>>> f
<function <lambda> at 0x7f95d8f85488>
>>> f(3)
27

the real lambda limitation is the fact that lambda must be a single expression; it can't contains keyword (like python2's print or return).

GvR choose to do so to limit the size of the lambda, as they normally are used as parameters. If you want a real function, use def

🌐
Wordpress
programmingideaswithjake.wordpress.com › 2016 › 10 › 01 › multi-line-lambdas-in-python
Multi-Line Lambdas in Python | Programming Ideas With Jake
January 12, 2018 - Python has one missing feature that actually hurts my idea that Kotlin is a lot like a statically-typed Python: lack of multi-line lambdas; lambdas in Python, as you probably know, are limited to a single expression or statement.
Top answer
1 of 4
9

In "indent-based languages" such as Python, indentation is needed at the statement level to determine the nesting of blocks. On the other hand, the nesting of expressions is defined without reference to indentation or any other whitespace, so there is no need to enforce any rules about indentation at the expression level, and arbitrary indentation is allowed when splitting expressions across multiple lines, either using backslash \ to ignore a line ending or writing inside brackets.

Both of these can be implemented directly in the lexer:

  • Recognise \\\n\s* (i.e. a literal backslash followed by a newline followed by any whitespace) as a whitespace token. It will then be ignored when parsing the expression, just like any other whitespace, and it won't get processed by the algorithm which tracks indentation at newlines because the newline character is part of the token.
  • The lexer counts the nesting level of brackets (increment a counter on each (, [ or { token, decrement on ), ] or }), and the algorithm which tracks indentation and inserts INDENT and DEDENT tokens ignores newlines when the counter is greater than zero. (A simple counter is enough, because if they don't match up correctly the parser will notice and report the error.)

This is all enough for lambda functions to span multiple lines when the body of the lambda is an expression ─ the user just has to ensure that either the lambda or its body is wrapped in parentheses, then it can span multiple lines. (Of course, this applies to every expression, not just lambdas.)


Lambda functions whose body is a block of statements, on the other hand, are considerably more difficult. Python's solution is to just not allow such lambdas; instead, you are supposed to declare a named function and then you can refer to it by name in an expression. There's a lot to be said for this approach ─ it means that expressions never contain statements, making the language grammatically simpler. It also results in more useful stack traces on runtime errors, because the lines have meaningful names instead of just saying <lambda>.

On the other hand, if you do want statements inside expressions, there's probably no way around having some kind of delimiters (like the braces in Rust), otherwise there will be nothing but whitespace separating the end of the last statement from the continuation of the expression that the lambda occurred in. Here's what it looks like without delimiters:

foo(lambda:
    print('hello world')
    do_something_else()
, 3.5)

Without block delimiters, the comma is required to be in this ugly position at the start of the line, and moreover the indentation of the expression matters on that line ─ it must be less indented than the lambda body ─ when indentation inside expressions doesn't matter anywhere else. These problems both disappear when you require delimiters; if you don't like braces in an indentation-based language, you could use Lua-style do/end keywords instead:

foo(lambda: do
    print('hello world')
    do_something_else()
end, 3.5)

So I think you have to just bite the bullet and use block delimiters, at least for statements that occur inside expressions. You don't need to require delimiters on every block, and you can still enforce the language's indentation rules between those delimiters; they're not there to define the nesting level of statements, they're there to separate the statements from the expression which contains them.

Implementation-wise, the lexer now needs to maintain a stack of those counters, so that when you see a do token it pushes a 0 to the stack, and when you see end it pops the counter from the stack. (No need to check that it's zero; the parser will ensure correct nesting of brackets.) This way you effectively "reset" the counter so that the lexer can insert the correct INDENT and DEDENT tokens inside the lambda body, while still being able to restore the old counter for the nesting level of the expression that the lambda occurs in.

2 of 4
4

Koka's trailing lambda syntax

The Koka language has an interesting feature called trailing lambdas: when the last argument of a function is a lambda, it can be written outside of the parentheses.

Let's take a look at this example (based on the example in kaya3's answer):

foo(3.5, fn()
    println('hello world')
    do_something_else()
)

The final right-parenthesis is ugly. Koka allows us to write this instead:

foo(3.5) fn()
    println('hello world')
    do_something_else()

Since this lambda doesn't take any arguments, the fn() can be omitted:

foo(3.5)
    println('hello world')
    do_something_else()

I think this is an elegant syntax sugar. There are some other languages that have similar feature, such as Julia and some early version of Rust, but those languages are not indent based.

Find elsewhere
🌐
Kodeclik
kodeclik.com › python-multiline-lambda
Can you write a multiline lambda in Python?
September 19, 2024 - Lambda functions are expected to be short and sweet and just contain one expression in their definition.You can split a single line lambda over multiple lines but you technically cannot write a lambda function that is more than a single expression.
🌐
Delft Stack
delftstack.com › home › howto › python › lambda multiple lines in python
Python Lambda With Multiple Lines | Delft Stack
February 12, 2024 - One straightforward way to write a multiline lambda is by enclosing the expression within parentheses and using backslashes to continue the code on the next line. This method is suitable for splitting a lambda function into multiple lines for ...
🌐
GitHub
github.com › NotShrirang › Multiline-lambda-Function
GitHub - NotShrirang/Multiline-lambda-Function: Multiline lambda function in python.
Multiline lambda function in python. Give arguments to lambdafunction() and include multiple lines of code in a single lambda function.
Author   NotShrirang
🌐
AppDividend
appdividend.com › 2022 › 06 › 15 › write-multilple-lines-lambda-in-python
Can you write Multilple Lines Lambda in Python?
July 11, 2023 - If you are a student or beginner in Web development, mobile development, and want to learn new languages, AppDividend is your best friend.
🌐
Quora
quora.com › Why-doesnt-Python-have-multiline-lambdas
Why doesn't Python have multiline lambdas? - Quora
Answer (1 of 3): First, it's probably worth noting that every feature doesn't exist until someone plans, implements, tests, and releases it. lambda and def are already almost the same. They both create function objects; the main difference is that lambda creates an anonymous function that can't ...
🌐
Verve AI
vervecopilot.com › interview-questions › what-are-the-hidden-rules-of-a-multiline-lambda-function-python-in-technical-interviews
What Are The Hidden Rules Of A Multiline Lambda Function Python In Technical Interviews?
A: True multiline lambdas (with multiple statements) are not possible. Breaking a single-expression lambda over lines for readability is acceptable but often a sign the logic might be better suited for a def function.
🌐
DigitalOcean
digitalocean.com › community › tutorials › lambda-expression-python
Python Lambda Expressions Explained with Examples | DigitalOcean
July 8, 2025 - A lambda expression in Python is ... expression. Lambda functions are often used when a small, one-time-use function is needed. ... No, a lambda expression cannot have multiple lines......
🌐
Wordpress
programmingideaswithjake.wordpress.com › 2018 › 01 › 13 › a-weird-and-mostly-impractical-way-to-do-multi-line-lambdas-in-python
A Weird (and Mostly Impractical) Way to Do Multi-Line “Lambdas” in Python | Programming Ideas With Jake
January 13, 2018 - This is the second time I’ve ... lambdas to exist in Python. The first time used the with block, as seen in the articles around creating Kotlin-like builders in Java and Python, and fully explained in its own article. Yes, there’s the obvious thing of defining the function just before passing it into the higher-order function, but the real problem with that is that it kind of separates the logic from its use. The function takes up at least two lines above its ...
🌐
Verve AI
vervecopilot.com › interview-questions › why-understanding-lambda-multiline-python-is-crucial-for-technical-interviews
Why Understanding Lambda Multiline Python Is Crucial For ...
Start FREE Today - Use the AI Interview Copilot for real-time, accurate answers to interview questions. Ace your job interviews confidently!
🌐
Verve AI
vervecopilot.com › interview-questions › why-multiline-lambda-python-isn-t-what-you-think-it-is-for-interview-success
Why Multiline Lambda Python Isn't What You Think It Is For Interview Success
A: No, the multi-line formatting of a single expression for readability (using parentheses) does not change the underlying structure or performance of the lambda. Q: Can I assign variables inside a multiline lambda Python?
🌐
Reddit
reddit.com › r/learnpython › returning a multi-line lambda function inside an outer function
r/learnpython on Reddit: Returning a multi-line lambda function inside an outer function
May 26, 2022 -

I am trying to return a multi-line function that takes one parameter inside an outer function. I cant use a lambda function since the body of the inner function spans across many lines.

def outer(a,b,c):

return lambda x : <multi-line function (uses a,b,c,x)> // not possible

I am also not allowed to create a new function for the inner function

Any suggestions?

🌐
Afternerd
afternerd.com › blog › python-lambdas
Python Lambdas Explained (With Examples) - Afternerd
April 6, 2019 - Yes, at some point in your life you will be wondering if you can have a lambda function with multiple lines. ... Python lambda functions accept only one and only one expression.