Python – The hidden ternary operator

Ever heard of the ternary operator? It is a key part of many programming languages, as it allows for shorthand if/else clauses and assignments. Consider this silly example of the ternary operator in JavaScript:

// Usual if/else clause
var canPass;

if (name === "Frodo") {
  canPass = "You shall pass.";
} else {
  canPass = "YOU SHALL NOT PASS!";

// The same condition, this time using the ternary operator
var canPass = name === "Frodo" ? "You shall pass." : "YOU SHALL NOT PASS!";

As handy as the ternary operator is, Python developers unfortunately have to put up with not having such a handy shortcut. Granted, our if/else clauses can be pretty compact thanks to our indentation-based, brace-less syntax, but it is still annoying at times.

# A compact Python if/else clause
if name == "Frodo":
    canPass = "You shall pass."
  canPass = "YOU SHALL NOT PASS!";

As it turns out, there actually is a ternary operator in Python, but it is not very well known.

canPass = "You shall pass." if name == "Frodo" else "YOU SHALL NOT PASS!"

As you can tell, the syntax and ordering is a tad different from the “normal” ternary operator:

variable = true value if condition else false value

Instead of testing the condition then setting the true value, we assign the variable the true value then test the condition. The false value is always set last (bit of “normalcy” there for you šŸ˜‰ ).

That is it for this tutorial! Truthfully, I wish I had known about this hidden ternary operator a lot sooner. I have been programming in Python for two years now and I had not heard of it until just the other day! If you would like to learn more, Wikipedia has a complete write-up about the operator’s usage and pitfalls. šŸ™‚