Python 101: The Ternary Operator

There are a lot of computer languages that include the ternary (or tertiary) operator, which is basically a one-line conditional expression in Python. If you’re interested, you can read about the various ways it’s rendered in other languages over on Wikipedia. Here we will spend some time looking at several different examples and why you might use this operator in real life.

I remember using the ternary operator in C++ where it was a question mark. I looked it up with Google and found some good example in a StackOverflow question and answer and in that aforementioned Wikipedia example. Let’s take a look at some of those and see if we can figure them out. Here is one of the simplest examples:

x = 5
y = 10
result = True if x > y else False

This basically reads as follows: The result will be True is x is greater than y, otherwise the result is False. To be honest, this reminds me mightily of some of the Microsoft Excel conditional statements I’ve seen. Some people object to this format, but it’s what the official Python documentation uses. The following is how you would write it in a normal conditional statement:

x = 5
y = 10

if x > y:

So you would save 3 lines of code by using the ternary operator. Anyway, you might want to use this structure when you’re looping over a set of files and you want to filter out some sections or rows. For our next example, we’ll loop over some numbers and check if they are odd or even:

for i in range(1, 11):
    x = i % 2
    result = "Odd" if x else "Even"
    print(f"{i} is {result}")

You would be surprised how often you have to check the remainder of a division statement. This is a quick way to tell if the number is odd or even though. In the previously mentioned StackOverflow link, there’s this funny piece of code that is shown as an example for those people who are still using Python 2.4 or older:

# (falseValue, trueValue)[test]
>>> (0, 1)[5>6]

>>> (0, 1)[5<6]


This is rather ugly, but it does the job. This is indexing a tuple and is certainly a hack, but it’s an interesting bit of code. Of course, it doesn’t have the short-circuit value of the newer method that we looked at previously, so both values are evaluated. You may even run into oddball errors doing it this way where True is False and vice-versa, so I don’t really recommend it.

There are also several ways to do the ternary with Python’s lambda. Here’s one from the Wikipedia entry mentioned earlier:

def true():
    return "truly"
def false():
    return "falsely"

func = lambda b,a1,a2: a1 if b else a2
func(True, true, false)()

func(False, true, false)()

This is some funky code, especially if you don’t understand how lambdas work. Basically, a lambda is an anonymous function. Here we create two normal functions and a lambda one. Then we call it with a boolean True and a False. In the first call, it’s read as follows: call the true function if boolean True, else call the false function. The second is slightly more confusing as it appears to say that you should call the true method if boolean False, but it’s really saying it will call the false method only if b is boolean False. Yeah, I find that a bit confusing too.

Wrapping Up

There are several other examples of ternary operators in the “additional reading section below that you can check out, but at this point you should have a pretty good grasp of how to use it and perhaps when you’d use it. I would personally use this methodology when I know I have a simple True/False conditional I need to make and I want to save a few lines of code. However, I often tend to go with explicit over implicit because I know that I’ll have to come back and maintain this code and I don’t like having to figure out weird stuff like this all the time, so I would probably just go ahead and write the 4 lines. The choice is yours, of course.

Additional Reading

8 thoughts on “Python 101: The Ternary Operator”

  1. Please don’t use example code like

    result = True if x > y else False

    I’ve seen code like this too often. It should be
    result = x > y

    But somehow – and in other languages than python as well – people seem to think assigning boolean expressions cannot be done.

  2. Your first sentence is wrong. It’s not a statement, it’s a conditional expression. That’s the whole point of it: it has a value, a statement does not.

  3. Pingback: Visto nel Web – 42 « Ok, panico

  4. Nitin Reddy Katkam

    You can probably use: “print(‘True’ if x > y else ‘False’)” for an exact conversion of the second code example that you’ve provided with if-conditional processing.

    BTW, are you using Python 2.x?

  5. Thanks! Most of the time, I am using Python 2.x, usually 2.6 or 2.7 although some of the machines at my current job still use 2.4

Comments are closed.