🌐
GeeksforGeeks
geeksforgeeks.org › python › ternary-operator-in-python
Ternary Operator in Python - GeeksforGeeks
The ternary operator can also be used in Python nested if-else statement.
Published   December 20, 2025
🌐
TutorialsPoint
tutorialspoint.com › ternary-operator-in-python
Ternary Operator in Python?
Many programming languages support ternary operator, which basically define a conditional expression. Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(conditi
🌐
W3Schools
w3schools.com › c › c_conditions_short_hand.php
C Short Hand If ... Else (Ternary Operator)
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... There is also a short-hand if...else, known as the ternary operator because it uses three operands.
🌐
W3Schools
w3schools.com › python › python_conditions.asp
Python If Statement
Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match
🌐
Mimo
mimo.org › glossary › python › ternary-operator
Python Ternary Operator: Syntax, Usage, and Examples
Just be cautious—nested ternary operators can quickly become difficult to read. ... numbers = [1, 2, 3, 4] length_status = "Long list" if len(numbers) > 3 else "Short list" print(length_status) This pattern is especially useful in data validation and summaries. Python code that processes collections often benefits from using ternary operator techniques for concise transformations.
🌐
Python Tips
book.pythontips.com › en › latest › ternary_operators.html
6. Ternary Operators — Python Tips 0.1 documentation
For the if-else ternary operator, it follows the normal if-else logic tree. Thus, if one case could raise an exception based on the condition, or if either case is a computation-heavy method, using tuples is best avoided. ... In python there is also the shorthand ternary tag which is a shorter version of the normal ternary operator you have seen above.
🌐
DataCamp
datacamp.com › tutorial › pythons-ternary-operators-guide
Python's Ternary Operators Guide: Boosting Code Efficiency | DataCamp
May 17, 2024 - In the context of tuples, the ternary operator selects one of two values based on a condition and returns it. This is achieved by indexing the tuple using the result of the condition as the index. If the condition is True, in Python True =1, the element at index 1 (corresponding to result_if_true) ...
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>)]
🌐
Dataquest
dataquest.io › blog › python-ternary-operator
Python Ternary: How to Use It and Why It's Useful (with Examples)
March 6, 2023 - In this tutorial, we'll discuss the Python ternary operator, its syntax, its advantages and limitations, and how to use it.
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_if_shorthand.asp
Python Shorthand If
If you have one statement for if and one for else, you can put them on the same line using a conditional expression: ... This is called a conditional expression (sometimes known as a "ternary operator").
🌐
iO Flood
ioflood.com › blog › python-ternary-operator
Python Ternary Operator | Usage Guide with Examples
February 4, 2024 - Python Booleans: The Definitive Guide – A guide by W3Schools that focuses on working with booleans in Python. All About Conditional Execution in Python – A Medium article that delves deep into conditional execution in Python. Python If-Else Statement – A FreeCodeCamp guide providing explanations on the use of conditional “if-else” statements in Python. Mastering the ternary operator ...
🌐
Flexiple
flexiple.com › python › python-ternary
Python ternary operators - How to use them? - Flexiple Tutorials - Flexiple
Learn how to use Python ternary operators efficiently with examples and explanations. Master this concise syntax for conditional expressions.
🌐
W3Schools
w3schools.com › python › python_operators.asp
Python Operators
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Operators are used to perform operations on variables and values.
🌐
W3Schools
w3schools.in › what-is-conditional-operator
What is Conditional Operator? - W3Schools
This operator is used for evaluating a specific condition which eventually affects to choose any one of the two Boolean values or expressions. The outcome of the entire evaluation comes as either true or false. It is unique in the sense because it is a ternary operator and there is only one ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › ternary operators in python
Ternary Operators in Python | Towards Data Science
January 15, 2025 - If it evaluates to False, the expression within the parenthesis following else will be evaluated, which is another ternary operator. Within this else expression, num1<num2 is evaluated. If it evaluates to True, num1 is returned. Otherwise, ‘equal’ is returned. Note: This is not necessarily a good solution since it can be confusing and difficult to read. Therefore, it is not Pythonic code.
🌐
freeCodeCamp
freecodecamp.org › news › python-tenary-operator
Python Ternary Operator – Conditional Operators in Python
April 26, 2023 - You can use conditional operators in Python to execute code based on a predefined condition(s). In this article, you'll learn how to use the ternary operator in Python. You'll see its syntax along with some practical examples. What Is the Ternary O...
🌐
DataFlair
data-flair.training › blogs › python-ternary-operator
Python Ternary Operator - 5 Ways To Implement Ternary Operators - DataFlair
July 14, 2025 - These are operators that test a condition and based on that, evaluate a value. Python packs a single-line “choose this or that” known as the ternary operator, or conditional expression. The form is value_if_true if condition else value_if_false.
🌐
Python Examples
pythonexamples.org › python-ternary-operator
Python Ternary Operator
Change the values for a, b and c, and try running the nested ternary operator. In this tutorial of Python Examples, we learned what Ternary Operator is in Python, how to use it in programs in different scenarios like basic example; executing statements inside Ternary Operator; nested Ternary Operator; etc., with the help of well detailed Python programs.
🌐
WsCube Tech
wscubetech.com › resources › python › ternary-operator
Ternary Operator in Python (Conditional Operator With Example)
October 1, 2025 - Learn how to use the Ternary Operator in Python, also known as the Conditional Operator, for concise one-line if-else statements in your Python code.
🌐
W3Schools
w3schools.com › python › gloss_python_if_else_shorthand.asp
Python Shorthandf If Else
Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match