Ternary Operator in Python - People got Clever
The ternary operator can be incredibly useful in numerous situations in Python, which is why I'm surprised that prior to Python 2.5, there was no standard way of using one. In this article, we'll cover the ternary operator that was added in Python 2.5 along with the numerous ways that people emulated the operator before then.
Python 2.5 or Greater
When PEP 308 was created, it finally added the ternary operator into the release of Python 2.5. Here is the syntax that Guido chose:
x = trueValue if condition else falseValue
By doing it this way, it makes it easy to follow it as trueValue to be the normal and falseValue to be the less common case. Here is an example:
print "The temperature is %s freezing." % ("below" if temp < 32 else "above")
In this example, Python will print to the console "The temperature is below freezing." if the variable temp is less than 32. Otherwise, it prints "The temperature is below freezing."
Python 2.4 or Less
People actually got rather clever and managed to create two ternary "operators" before Python 2.5 came to be. One relies on tuples and the other relies on rather funky logic.
x = (falseValue, trueValue)[condition]
The above code is the way I see used more out in the wild with older scripts. It works based on the fact that a condition evaluated to True or False, which is equivalent to 1 or 0 respectively. Once the condition is evaluated, it gets used as an index for the tuple being used. Here is another less common way:
x = condition and trueValue or falseValue
This version works because if the condition evaluates to True (or 1), then trueValue will be chosen since 'anding' the two won't return False, and thus will select the trueValue. The opposite is true when the 'anding' results in False, at which point the other value in the 'or' will be chosen. This version is highly discouraged because it is impossible to have trueValue be equal to False since it'll break the logic. There are a few workarounds for this, but it only makes it more confusing.
Background
In my opinion, he chose the best of those that were available. It continues Python's long history of readability and the zen of python (if you don't know what that is, type 'import this' into the python console); however, there were numerous styles that the community proposed:
if C then x else y (if C: x else: y) C ? x : y C ? x ! y cond(C, x, y) C then x else y C ? x else y C -> (x, y)
Yes, yes, I know. Most of these are ugly and few actually represent what a Python junkie would enjoy using, which is why I'm glad that Guido chose what he did over the standard in most languages:
x = (condition)? trueValue : falseValue

Leave a comment