August 10, 2022

Python Ternary: How to Use It and Why It’s Useful (with Examples)

Python Ternary Operator

What is a Python ternary operator, and when is it useful? This tutorial will walk you through everything you need to know.

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. In other words, it’s a compact alternative to the common multiline if-else control flow statements in situations when we only need to "switch" between two values. The ternary operator was introduced in Python 2.5.

The syntax consists of three operands, hence the name "ternary":

a if condition else b

Here are these operands:

  • condition — a Boolean expression to test for true or false
  • a — the value that will be returned if the condition is evaluated to be true
  • b — the value that will be returned if the condition is evaluated to be false

The equivalent of a common if-else statement, in this case, would be the following:

if condition:
    a
else:
    b

Let’s look at a simple example:

"Is true" if True else "Is false"
'Is true'

While the ternary operator is a way of re-writing a classic if-else block, in a certain sense, it behaves like a function since it returns a value. Indeed, we can assign the result of this operation to a variable:

my_var = a if condition else b

For example:

x = "Is true" if True else "Is false"
print(x)
Is true

Before we had the ternary operator, instead of a if condition else b, we would use condition and a or b. For example, instead of running the following . . .

True if 2 > 1 else False
True

. . . we would run this:

2 > 1 and True or False
True

However, if the value of a in the syntax condition and a or b evaluates to False (e.g., if a is equal to 0, or None, or False), we would receive inaccurate results. 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:

False if 2 > 1 else True
False

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:

2 > 1 and False or True
True

To avoid such issues, it’s always better to use the ternary operator in similar situations.

Limitations of Python Ternary Operator

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. Otherwise, the program throws an error:

1 if True else x = 0
  File "C:\Users\Utente\AppData\Local\Temp/ipykernel_13352/3435735244.py", line 1
    1 if True else x=0
    ^
SyntaxError: cannot assign to conditional expression

If we need to use statements, we have to write a full if-else block rather than the ternary operator:

if True:
    1
else:
    x=0

Another limitation of the Python ternary operator is that we shouldn’t use it for testing multiple expressions (i.e., the if-else blocks with more than two cases). Technically, we still can do so. For example, take the following piece of code:

x = -1

if x < 0:
    print('x is less than zero')
elif x > 0:
    print('x is greater than zero')
else:
    print('x is equal to 0')
x is less than zero

We can rewrite this code using nested ternary operators:

x = -1
'x is less than zero' if x < 0 else 'x is greater than zero' if x > 0 else 'x is equal to 0'
'x is less than zero'

(Side note: In the above piece of code, we omitted the print() statement since the Python ternary operator always returns a value.)

While the second piece of code looks more compact than the first one, it’s also much less readable. To avoid readability issues, we should opt to use the Python ternary operator only when we have simple if-else statements.

How to Use a Python Ternary Operator

Now, we’ll discuss various ways of applying the Python ternary operator. Let’s say we want to check if the water at a certain temperature is boiling or not. At standard atmospheric pressure, water boils at 100 degrees Celsius. Suppose that we want to know if the water in our kettle is boiling given that its temperature reaches 90 degrees Celsius. In this case, we can simply use the if-else block:

t = 90

if t >= 100:
    print('Water is boiling')
else:
    print('Water is not boiling')
Water is not boiling

We can re-write this piece of code using a simple Python ternary operator:

t = 90
'Water is boiling' if t >= 100 else 'Water is not boiling'
'Water is not boiling'

(Side note: above, we omitted the print() statement since the Python ternary operator always returns a value.)

The syntax for both pieces of code above is already familiar. However, there are some other ways to implement the Python ternary operator that we haven’t considered yet.

Using Tuples

The first way to re-organize the Python ternary operator is by writing its tupled form. If the standard syntax for the Python ternary operator is a if condition else b, here we would re-write it as (b, a)[condition], like this:

t = 90
('Water is not boiling', 'Water is boiling')[t >= 100]
'Water is not boiling'

In the syntax above, the first item of the tuple is the value that will be returned if the condition evaluates to False (since False==0), while the second is the value that will be returned if the condition evaluates to True (since True==1).

This way of using the Python ternary operator isn’t popular compared to its common syntax because, in this case, both elements of the tuple are evaluated since the program first creates the tuple and only then checks the index. In addition, it can be counterintuitive to identify where to place the true value and where to place the false value.

Using Dictionaries

Instead of tuples, we can also use Python dictionaries, like this:

t = 90
{True: 'Water is boiling', False: 'Water is not boiling'}[t >= 100]
'Water is not boiling'

Now, we don’t have the issue of differentiating between the true and false values. However, as with the previous case, both expressions are evaluated before returning the right one.

Using Lambdas

Finally, the last way of implementing the Python ternary operator is by applying Lambda functions. To do so, we should re-write the initial syntax a if condition else b in the following form: (lambda: b, lambda: a)[condition]()

t = 90
(lambda: 'Water is not boiling', lambda: 'Water is boiling')[t >= 100]()
'Water is not boiling'

Note that in this case, we can become confused about where to put the true and false values. However, the advantage of this approach over the previous two is that it performs more efficiently because only one expression is evaluated.

Conclusion

Let’s sum up what we learned in this tutorial about the Python ternary operator:

  • How the Python ternary operator works
  • When its preferable to a common if-else block
  • The syntax of the Python ternary operator
  • The equivalent of the Python ternary operator written in a common if-else block
  • The old version of the Python ternary operator and its problems
  • The limitations of the Python ternary operator
  • Nested Python ternary operators and their effect on code readability
  • How to apply the Python ternary operator using tuples, dictionaries, and Lambda functions — including the pros and cons of each method
Elena Kosourova

About the author

Elena Kosourova

Elena is a petroleum geologist and community manager at Dataquest. You can find her chatting online with data enthusiasts and writing tutorials on data science topics. Find her on LinkedIn.

Learn data skills for free

Headshot Headshot

Join 1M+ learners

Try free courses