Python Gem #2: ternary operator

Adam Short
Aug 27, 2017 · 1 min read

Python if/else statements are very readable:

if x:
... do things ...
else:
... do things ...

The downside is that it takes 4 lines even if you want to do something as simple as setting a variable:

if x:
a = 5
else:
a = 6

The solution? Ternary Operators!

a = 5 if x else 6 # variable assignmentreturn a if y > 10 else b # returns a or b

Ternary operators actually work different to an if statement despite just looking like a one line version of the same thing:

<value> if <condition> else <value>

This is a daily series called Python Gems. Each short posts covers a detail or a feature of the python language that you can use to increase your codes readability while decreasing its length.

)

Adam Short
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade