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'))
 
Output:
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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github