1 if A else 2 if B else 3 translates to this:

def myexpr(A, B):
    if A:
        return 1
    else:
        if B:
            return 2
        else:
            return 3

Your ternary expression can be interpreted with parentheses as follows:

(
 (1 if A) else (
                (2 if B) else 3
               )
)
Answer from inspectorG4dget on Stack Overflow
Top answer
1 of 5
28

1 if A else 2 if B else 3 translates to this:

def myexpr(A, B):
    if A:
        return 1
    else:
        if B:
            return 2
        else:
            return 3

Your ternary expression can be interpreted with parentheses as follows:

(
 (1 if A) else (
                (2 if B) else 3
               )
)
2 of 5
7

Could someone please explain why this is executed in this order, and possibly suggest some material that gives an intuition about why this is used/preferred?

I'm trying to answer the "intuition" part of your question by solving a simple but more general problem.

'''
+-----------------------------------------------------------------------------------+
|                                    Problem:                                       |
+-----------------------------------------------------------------------------------+
| Convert a                                                                         |
| nested if-else block into                                                         |
| a single line of code by using Pythons ternary expression.                        |
| In simple terms convert:                                                          |
|                                                                                   |
|      1.f_nested_if_else(*args) (  which uses                                      |
|      ````````````````````        nested if-else's)                                |
|            |                                                                      |
|            +--->to its equivalent---+                                             |
|                                     |                                             |
|                                     V                                             |
|                              2.f_nested_ternary(*args) (     which uses           |
|                              ```````````````````       nested ternary expression) |
+-----------------------------------------------------------------------------------+
'''
'''
Note:
C:Conditions  (C, C1, C2)
E:Expressions (E11, E12, E21, E22)
Let all Conditions, Expressions be some mathematical function of args passed to the function
'''    

#-----------------------------------------------------------------------------------+
#| 1. |      Using nested if-else                                                   |
#-----------------------------------------------------------------------------------+
def f_nested_if_else(*args):
    if(C):
        if(C1):
            return E11
        else:
            return E12
    else:
        if(C2):
            return E21
        else:
            return E22

#-----------------------------------------------------------------------------------+
#| 2. |      Using nested ternary expression                                        |
#-----------------------------------------------------------------------------------+
def f_nested_ternary(*args):
    return ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )


#-----------------------------------------------------------------------------------+
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------+

Here is a visualization of why f_nested_if_else() and f_nested_ternary() are equivalent.

#     +-----------------------------------------------------------------------------+
#     |                               Visualization:                                |
#     +-----------------------------------------------------------------------------+
#     |         Visualize the ternary expression like a binary tree :               |
#     |           -Starting from the root and  moving down to the leaves.           |
#     |           -All the internal nodes being conditions.                         |
#     |           -All the leaves being expressions.                                |
#     +-----------------------------------------------------------------------------+
                                     _________________
                                     |f_nested_ternary|                                 
                                     ``````````````````
            ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )
                |       |        |          |            |       |        |
                |       |        |          |            |       |        |
                V       V        V          V            V       V        V                                                                             
Level-1|                  +----------------(C)-----------------+         
--------             True/          __________________           \False         
                        V           |f_nested_if_else|            V              
Level-2|          +----(C1)----+    ``````````````````     +----(C2)----+     
--------     True/              \False                True/              \False
                V                V                       V                V     
Level-3|    ( (E11)            (E12) )               ( (E21)            (E22) ) 
------------------------------------------------------------------------------------+

Hope this visualization gave you an intuition of how nested ternary expressions are evaluated :P

๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ pythons-ternary-operators-guide
Python's Ternary Operators Guide: Boosting Code Efficiency | DataCamp
May 17, 2024 - The nested ternary operator in Python allows you to combine multiple conditional expressions within a single ternary operator.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ ternary-operator-in-python
Ternary Operator in Python - GeeksforGeeks
We can nest ternary operators to evaluate multiple conditions in a single line. ... First, it checks if num > 0. If True, it returns "Positive". If False, it checks if num < 0. If True, it returns "Negative".
Published ย  December 20, 2025
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ one line if else and nested if statements in python ( ternary operator)
r/Python on Reddit: One line if else and nested if statements in python ( ternary operator)
July 5, 2020 - One ternary is often confusing enough, nesting them makes the code unnecessarily unreadable. when your colleagues or (more often) you read this code in 6 months you will thank yourself for not doing this. there is no advantage in doing this instead of using elif statements ... And I'd even say be also careful with simple ternary operators too.
๐ŸŒ
Wiingy
wiingy.com โ€บ home โ€บ learn โ€บ python โ€บ ternary operators in python
Ternary Operators in Python
January 30, 2025 - The nested ternary operator checks if the numberis zero by evaluating num == 0. If the condition is true, the nested ternary operator returns the string โ€œzeroโ€. If both the first and nested conditions are false, the ternary operator returns ...
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-ternary-operator
Python Ternary Operator
This example demonstrates that you can run any Python function inside a Ternary Operator. You can nest a ternary operator in another statement with ternary operator.
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ python-ternary-operator
Python Ternary Operator - 5 Ways To Implement Ternary Operators - DataFlair
July 14, 2025 - We can also make use of Python Lambda Functions to act as a ternary operator. ... >>> a=random() >>> "Less than zero" if a<0 else "Between 0 and 1" if a>=0 and a<=1 else "Greater than one" ...
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ python-ternary-operator
Guide to Using Ternary Operator in Python | Codecademy
When using the ternary operator ... conditions that can be easily understood at a glance. Avoid Nesting: Limit the nesting of the ternary operator ......
Find elsewhere
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python nested multiple ternary operators
Python Nested Multiple Ternary Operators - Be on the Right Side of Change
December 23, 2021 - Short Answer: The nested ternary operator '1' if x else '2' if y else '3' evaluates the condition from left to right, i.e., '1' if x else ('2' if y else '3'). In short, first condition first!
๐ŸŒ
Igmguru
igmguru.com โ€บ blog โ€บ ternary-operator-in-python
Ternary Operator in Python: Complete Tutorial for Beginners
1 week ago - There is no significant performance difference between the ternary operator and a traditional if-else statement. These both are evaluated efficiently by Python. The main advantage of the ternary operator is cleaner and shorter syntax for simple conditions. Yes, multiple conditions can be used by nesting ternary operators.
๐ŸŒ
Enterprise DNA
blog.enterprisedna.co โ€บ ternary-operator-in-python-what-how-why
Ternary Operator in Python โ€“ What? How? Why? โ€“ Master Data Skills + AI
When using the ternary operator in Python, there are some best practices and tips to help you write clean, efficient, and readable code. Firstly, ensure that your conditional expression is short and concise. Long and complex conditions might make it difficult to understand the logic behind the ternary operator. If you find yourself facing a complex condition, it might be better to use a regular if-else statement instead. #demonstrate nested ternary operator # Good example result = "positive" if number >= 0 else "negative" # Bad example result = (a + b if (x > 10 and y > 20) else c + d) if (z > 30 and p > 40) else ...
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ python-ternary-operator
Python Ternary: How to Use It and Why It's Useful (with Examples)
March 6, 2023 - The Python ternary operator (or conditional operator), tests if a condition is true or false and, depending on the outcome, returns the corresponding value โ€” all in just one line of code.
๐ŸŒ
Python Geeks
pythongeeks.org โ€บ python geeks โ€บ learn python โ€บ python ternary operator with example
Python Ternary Operator with Example - Python Geeks
June 14, 2022 - # Take Input of Number no = int(input()) # Nested Ternary Operators Implementation PythonGeeks_result = "Negative Number" if no<0 else "Number is Zero" if no==0 else "Positive Number" # Displaying the result print("Result for ",no," : ",PythonGeeks_result)
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ python โ€บ ternary operator in python
Ternary Operator in Python - Scaler Topics
April 21, 2023 - We can nest ternary operators by chaining them. We should avoid nesting as it may hurt readability. Also, check out this article to learn about Operators in Python.
๐ŸŒ
DEV Community
dev.to โ€บ askyt โ€บ python-ternary-operator-a-comprehensive-guide-274i
Python Ternary Operator: A Comprehensive Guide - DEV Community
December 14, 2024 - The ternary operator simplifies ... than zero" if x > 0 else "Equal to zero" print(result) ... Note: While nesting is possible, it can harm readability....
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ ternary-operator
Python Ternary Operator: Syntax, Usage, and Examples
Python doesnโ€™t allow assignment expressions like JavaScript does. ... Each case allows you to replace bulky conditional logic with one clear, compact line. The Python ternary operator gives you a flexible and readable way to handle conditional assignments and expressions.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-ternary-operator
Python Ternary Operator | Usage Guide with Examples
February 4, 2024 - As a best practice, avoid nesting ternary operations more than once. If your code requires more complex conditional logic, consider using traditional if-else statements for clarity. Remember, the goal of using the ternary operator should be to make your code more readable and efficient, not less. While the ternary operator is a powerful tool, Python ...
๐ŸŒ
AlgoMaster
algomaster.io โ€บ learn โ€บ python โ€บ ternary-operator
Ternary Operator | Python | AlgoMaster.io | AlgoMaster.io
Use for Simple Conditions: Reserve the ternary operator for straightforward cases where it enhances readability. Avoid Excessive Nesting: Limit nesting to maintain clarity.
Top answer
1 of 16
9351

Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use statements such as pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression:

>>> pass if False else pass
  File "<stdin>", line 1
    pass if False else pass
         ^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
  File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
  File "<stdin>", line 1
    (x = 1) if False else (y = 2)
       ^
SyntaxError: invalid syntax

(In 3.8 and above, the := "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)

Similarly, because it is an expression, the else part is mandatory:

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Or for example to return a value:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
    return a if a > b else b

Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal if statement instead.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition ? a : b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)

If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

  • Conditional expressions
  • Is there an equivalent of Cโ€™s โ€?:โ€ ternary operator?
2 of 16
1028

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.
It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]