The world’s leading publication for data science, AI, and ML professionals.

Better Pythoning 1: Ternary Operators

How to shorten lines of code and make it more readable with a few simple steps.

Image taken from hiteshchoudhary
Image taken from hiteshchoudhary

If you are a beginner in Data Science, it is likely that you’ve come across Ternary Operators (cool one-line if-statements). Have you wondered what they are, why they are ubiquitous and when they should be used?

In this article, I’m going to briefly explain ternary operators with examples to make them digestible. This is the first of a four-part series on using one-line statements to shorten code (i.e. List Comprehensions, Lambda Functions, etc.). The final article in the series will teach you how to combine these different methods to shorten your code substantially. I hope readers enjoy reading this article, learn something new but also improve the readability of their code.


Ternary Operators – or as I call them fancy if-statements

In Python, an IF statement allows you to run certain parts of your code when certain conditions are. A quick example:

Naturally, this can be expanded to include more complex commands. A Ternary Operator can achieve much of what an if statement does in one line, for example:

This can be read quite literally as: print('I have a name') if my_name is truthy otherwise print('I dont have a name') .

truthy refers to things that Python reads as boolean True . This can be pretty much anything, with some notable exceptions (these are known as falsy), such as an empty list [] , a zero 0 , an empty string, '' , etc.

This is very useful when the only function of an if statement is to set variables. For example:

Note that this is quite a trivial example that can be made even simpler by setting is_retired = age > retirement_age .

The point is that ternary operators are not actually statements per se, they actually return a value. This means that the statement True if age > retirement_age else False is like a function that will return a value after it is run.

An if-statement on the other hand, does not, on its own, return any value. It is what is actually inside the if-statement that returns values or not. This is quite important because functions such as raise cannot be used in ternary operators because they do not actually return anything.

So, if that’s the case, how come the first ternary operator with print worked? In fact this does not violate the rule: print returns None when it is run.

If you doubt this, try setting a = print('Hello World') , then print(a)

This means when we did print('I have a name') if my_name else print('I dont have a name') we actually returned None , but we didn’t specify a variable to store that value!

One final complication: Ternary operators can also take in values to functions. This is explained below:

It’s worth calling attention to the fact that the functions difference and print in the ternary operator do not have any brackets. The brackets outside the whole thing means that those are actually functions that take (retirement_age, age) as variables. Though this is cool, it is not typically something which is used very often, and it overcomplicates code, so it is best to avoid.

Key takeaways:

  • A ternary operator is a one-line if-statement looking like operator that must return value(s) depending on the conditions
  • This means that they are very useful for setting variables, but not for running code
  • Ternary operators can be chained, for example: my_surname = 'Unchained' if my_name.lower() == 'django' else 'Fett' if my_name.lower() == 'jango' else 'Surnameless'
  • Ternary operators can be written in an alternate forms, these are shown below
  • It’s worth noting that ternary operators only really improve readability when setting variables, more complex use cases are better reserves for if-statements


Conclusion

Ternary Operators are:

  • quite powerful for making code readable (when used sensibly to return variables)
  • make your code shorter when used for simple expressions

Overall, I find them quite nicer than if-statements and end up using them quite often, especially since they don’t have a significant impact on efficiency (see Appendix).

It’s worth noting that these operators become much more powerful when used inside other functions and expressions, such as List Comprehensions (again, these are cool one-line for loops), which is the topic of the next article. In it, I’ll give examples of where they can be of quite use in real Data Science problems. A brief sneak peak into List Comprehensions:


Appendix

This is a little experiment I ran to see if ternary operators have any impact on efficiency (according to Stack Overflow, they shouldn’t)

I compared two for loops with identical variables inside that use either a ternary operator or an if-statement to set it. I then repeated the experiment 100 times, calculating the time difference for each run. The code and results are shown below:

We can see from the above that the ternary operator is a bit slower, roughly ~2.5% which is quite small.


Related Articles