How to use the ternary conditional operator in Python?

Better Stack Team
Updated on January 24, 2023

The ternary conditional operator is a shortcut when writing simple conditional statements. If the condition is short and both true and false branches are short too, there is no need to use a multi-line if statement.

If you come from a different language, you will notice that the python version of the ternary conditional operator is slightly different than in other languages. It looks like this

on_true() if condition else on_false()

In the example above, if the condition is evaluated to be true, the on_true function will be executed, otherwise, on_false will be executed. Here is a practical example:

number = 5
print('Number is ' + ('even' if number % 2 == 0 else 'odd'))
Number is odd

As you can see, the ternary operator can be used on its own, or it can even be used as a part of the argument in the function call as seen in the example above. But there is more.

Selecting from a tuple or dictionary

We can shorten this even more. You can wrap the condition into [] brackets and drop the if and else keyword together. Then you can use a tuple for selecting the value based on the result of the condition in the brackets. The same can be done using a dictionary with the True and False keys.

Note the order in the tuple example.

number = 5

# using tuple
# also note the different order here
print('Number is ' + (('odd', 'even')[number % 2 == 0 ]))

# using dictionary
print('Number is ' + ({True: 'even', False: 'odd'}[number % 2 == 0 ]))
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack