Last Updated: Wednesday 31st December 2014

Basic if statement (ternary operator) info

Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression.

Programming languages derived from C usually have following syntax:

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic, since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its own shortcut conditional expression:

It first evaluates the condition; if it returns True, expression1 will be evaluated to give the result, otherwise expression2. Evaluation is lazy, so only one expression will be executed.

Let's take a look at this example:

Ternary operators can be changed:

Which is the same as:

Conditions are evaluated from left to right, which is easy to double-check with something like the pprint module:

Alternatives to the ternary operator

For Python versions lower then 2.5, programmers developed several tricks that somehow emulate behavior of ternary conditional operator. They are generally discouraged, but it's good to know how they work:

The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:

Another approach using and/or statements:

Yes, most of the workarounds look ugly. Nevertheless, there are situations when it's better to use and or or logic than the ternary operator. For example, when your condition is the same as one of expressions, you probably want to avoid evaluating it twice:

Use Python magic carefully!

For more about using if statements on one line (ternary conditional operators), checkout PEP (Python Enhancement Proposal) 308.

About The Author