The Ternary Operator Trick In Python

1 Sep

The Ternary Operator is really handy for refactoring a simple if else statement into one line of code. Unfortunately, Python doesn’t have the standard ? : operator built in. So, what should you do to refactor your code?


Update: I just found via this StackOverflow answer that Python versions 2.5 and higher have the following syntax for the Ternary operator:

a if test else b

So, for the below example, the code would be:

>>> a = "I'm first"
>>> b = "I'm last"
>>> a if True else b
"I'm first"

Keep reading if you’re interested in the cool trick anyway 🙂

The Boolean Logic Trick

According to Dive into Python, you can instead use simple boolean logic to accomplish the ternary operation. Try this in your python shell (simply type “python” in the command line of your Terminal):


>>> a = "I'm first!"

>>> b = "I'm last!"

>>> True and a or b
"I'm first!"

>>> if 1:
...     a
... else:
...     b
... 
"I'm first!"

>>> 1 and a or b
"I'm first!"

>>> False and a or b
"I'm last!"

>>> if 0:
...     a
... else:
...     b
... 
"I'm last!"

>>> 0 and a or b
"I'm last!"

As you can see, if the “and” statement is evaluated to True, then the last item of the and statement is returned (in this case a). Alternatively, if the “and” statement is evaluated to False, the last item of the or statement is returned (in this case b).

When The Trick Goes Horribly Wrong

However, there is a bit of loophole with this logic! If a is a falsy value, then the “and” statement is evaluated to False and b is returned instead of a, even if the first item is evaluated to True!

So, for example:

>>> a = ""
>>> b = "I'm last"

>>> if 1:
...     a 
... else:
...     b
... 
''
>>> 1 and a or b
"I'm last"

The Fix

If there is a possibility that a could be a false value, make sure to add a and b as a list item, so it is always truthy, regardless of whether the value of a or b is falsy:

>>> a = ""
>>> b = "I'm last"
>>> (1 and [a] or [b])[0]
''

Since “(1 and [a] or [b])[0]” doesn’t seem like a very easy to read if else statement, I’m not sure how often Python programmers actually use it.

If you write in Python, do you use this trick often?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s