Python Gem #2: ternary operator
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 = 6The 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.