Why use ternary operator in Python

Sat 14 September 2013
By Tianyi

I used to write something like:

    # a, b and c are variables
    x = a and b or c

It's quite simple, what I want is if a is a trueish value like True, != 0 or not an empty string, x will become b, otherwise it will become c.

But recently I learned there are some logical loopholes using this method. And then I also learned the Conditional Expressions also known as the Ternary Operator was added in Python 2.5 and it's a better way to achieve the same effect as the example above. Its syntax is quite different compare to other languages though. The Ternary Operator syntax in Python is like:

    x = b if a else c

This has the same effect as the and or example. Then why is this better? What are the loopholes by using the and or?

Using the same example, if b is False,

    x = a and False or c

The result of x will always be c, because a and False is always False and False or c is always c. But what I want is if a has trueish value, I want x to be False, else let it be c. So just like I described, using the Ternary Operator:

    x = False if a else c

There we go, x will be False now which fixed the problem I had for using and or.

I suppose I still can use and or if I am sure that b is never gonna be False, but if I use the Ternary Operator, I don't need to worry about b's value at all.