Ternary operators in python act as follows:

condition = True
foo = 3.14 if condition else 0

But for your particular use case, you should consider using dict.get(). The first argument specifies what you are trying to access, and the second argument specifies a default return value if the key does not exist in the dictionary.

some_dict = {'a' : 1}

foo = some_dict.get('a', '') # foo is 1
bar = some_dict.get('b', '') # bar is ''
Answer from MichVaz on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › ternary-operator-in-python
Ternary Operator in Python - GeeksforGeeks
Explanation: This defines an anonymous function (lambda) that takes two arguments and returns the larger one using the ternary operator. It is then called with a and b. The ternary operator can also be directly used with the Python print statement.
Published   December 20, 2025
🌐
Mimo
mimo.org › glossary › python › ternary-operator
Python Ternary Operator: Syntax, Usage, and Examples
The ternary operator (also called ... Syntax:value_if_true if condition else value_if_false · The condition is evaluated first. If the condition is True, value_if_true is returned....
🌐
Syntaxdb
syntaxdb.com › ref › python › ternary
Ternary Operator in Python - SyntaxDB - Python Syntax Reference
result = value_returned_if_true if boolean_expression else value_returned_if_false · The ternary operator cannot include statements in any of its three parts.
🌐
TutorialsPoint
tutorialspoint.com › ternary-operator-in-python
Ternary Operator in Python?
However, it also returns a value so behaving similar to a function. ... With ternary operator, we are able to write code in one line. So python basically first evaluates the condition, if true – evaluate the first expression else evaluates the second condition.
🌐
DataFlair
data-flair.training › blogs › python-ternary-operator
Python Ternary Operator - 5 Ways To Implement Ternary Operators - DataFlair
July 14, 2025 - Tags: Nested ternary Operator in pythonPython and orPython Conditional expressionPython If elsePython If StatementPython TernaryPython Ternary returnPython Ternary without elseTernaryTernary Operator
🌐
Python Tips
book.pythontips.com › en › latest › ternary_operators.html
6. Ternary Operators — Python Tips 0.1 documentation
In python there is also the shorthand ... Python 2.5 and can be used in python 2.5 or greater. ... The first statement (True or “Some”) will return True and the second statement (False or “Some”) will return Some....
Find elsewhere
🌐
Python Examples
pythonexamples.org › python-ternary-operator
Python 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. Python datetimePython flaskPython jsonPython loggingPython mathPython mysqlPython MatplotlibPython nltkPython numpyPython opencvPython pandasPython phonenumbersPython picklePython pillowPython pymongoPython randomPython requestsPython seleniumPython sqlite3Python tkinter
🌐
Scaler
scaler.com › home › topics › python › ternary operator in python
Ternary Operator in Python - Scaler Topics
April 21, 2023 - False value: A value (any Python object) to return if the condition is evaluated to False. ... The ternary operator includes a condition to evaluate, a true value, and a false value to return based on that condition.
🌐
Sentry
sentry.io › sentry answers › python › does python have a ternary conditional operator?
Does Python Have a Ternary Conditional Operator? | Sentry
The operator checks a condition, and returns x if the condition is true or y if it’s not. Here is an example of a ternary operator use case: ... The ternary operator above checks if x is greater than y, and if it is, assigns the value of x (10) to the variable z. If you’re looking for information on Python ...
🌐
Wiingy
wiingy.com › home › learn › python › ternary operators in python
Ternary Operators in Python
January 30, 2025 - The syntax for the ternary operator in Python is as follows: ... Here, expression is a boolean expression, and on_true and on_false are the values that are returned based on the result of the boolean expression.
🌐
Finxter
blog.finxter.com › python-one-line-ternary
Python One Line Ternary – Be on the Right Side of Change
The ternary operator returns the value associated to the given key—but only if the key exists. If it doesn’t exist, it returns the default value -1. However, a more Pythonic way to accomplish the same thing in a more readable and more concise way is to use the dictionary.get(key, default) ...
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 - The example of a ternary operator below looks logically controversial (we want to return False if 2 > 1; otherwise, we want to return True) but it is technically correct since it's up to us to decide which value to return if the condition evaluates to True — and which value to return if the condition evaluates to False. In this case, we expect False, and we got it: ... Using the "old-style" syntax instead of the ternary operator for the same purpose, we would still expect False. However, we received an unexpected result: ... To avoid such issues, it's always better to use the ternary operator in similar situations. Note that each operand of the Python ternary operator is an expression, not a statement, meaning that we can't use assignment statements inside any of them.
🌐
FavTutor
favtutor.com › blogs › ternary-operator-python
Python Ternary Operator With Examples | FavTutor
Learn what is ternary operator in python with various methods to implement it along with examples and output.
🌐
DataCamp
datacamp.com › tutorial › pythons-ternary-operators-guide
Python's Ternary Operators Guide: Boosting Code Efficiency | DataCamp
May 17, 2024 - The syntax of a ternary operator in Python is value_if_true if condition else value_if_false. It evaluates the condition first; if it's true, it returns value_if_true; otherwise, it returns value_if_false
🌐
Hackr
hackr.io › home › articles › programming
Python Ternary Operator: How and Why You Should Use It
January 30, 2025 - We can easily write a ternary expression in Python if we follow the general form shown below: var_result = true_value if [condition] else false_value · So, we start by choosing a condition to evaluate against. Then, we either return the true_value or the false_value and then we assign this to results_var. If we consider that a ternary operator is a single-line statement and an if-else statement is a block of code, then it makes sense that if-else will take longer to complete, which means that yes, the ternary operator is faster.
🌐
Pi My Life Up
pimylifeup.com › home › how to use the python ternary operator
How to use the Python Ternary Operator - Pi My Life Up
July 8, 2022 - Unfortunately, this difference can lead to Python novices making mistakes when using the operator. Our ternary operator works by first evaluating the condition and then running true_val or false_val depending on the result of the condition.