# The Ternary Operator Trick In Python

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:

```&gt;&gt;&gt; a = &quot;I'm first&quot;
&gt;&gt;&gt; b = &quot;I'm last&quot;
&gt;&gt;&gt; a if True else b
&quot;I'm first&quot;
```

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):

```
&gt;&gt;&gt; a = &quot;I'm first!&quot;

&gt;&gt;&gt; b = &quot;I'm last!&quot;

&gt;&gt;&gt; True and a or b
&quot;I'm first!&quot;

&gt;&gt;&gt; if 1:
...     a
... else:
...     b
...
&quot;I'm first!&quot;

&gt;&gt;&gt; 1 and a or b
&quot;I'm first!&quot;

&gt;&gt;&gt; False and a or b
&quot;I'm last!&quot;

&gt;&gt;&gt; if 0:
...     a
... else:
...     b
...
&quot;I'm last!&quot;

&gt;&gt;&gt; 0 and a or b
&quot;I'm last!&quot;
```

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:

```&gt;&gt;&gt; a = &quot;&quot;
&gt;&gt;&gt; b = &quot;I'm last&quot;

&gt;&gt;&gt; if 1:
...     a
... else:
...     b
...
''
&gt;&gt;&gt; 1 and a or b
&quot;I'm last&quot;
```

# 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:

```&gt;&gt;&gt; a = &quot;&quot;
&gt;&gt;&gt; b = &quot;I'm last&quot;
&gt;&gt;&gt; (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?

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.