The ternary operator in Python
python

The ternary operator in Python

The ternary operator ?: is part of the syntax in different programming languages used for conditional expressions. Is also known as conditional operator, inline if or just ternary if. Now, this is the theory which looks nice! But, how about in Python?

Given the expression:

if <condition> then
  <whenIsTrue>
else
  <whenIsFalse>

That is referred as the normal way to evaluate a condition and execute one of two possible options, in this case, whenIsTrue or whenIsFalse. Using the ternary operator ?: we can write these expression in just one line as:

<condition> ? <whenIsTrue>: <whenIsFalse>

When condition is True the instruction whenIsTrue is executed, otherwise the instruction whenIsFalse is evaluated.

This sentence is called the ternary operator, commonly implemented in different programming languages, but Python is an exception.

Conditional expression

Python does not implement directly the ternary operator, but it implements something called conditional expression which should be written as:

<whenIsTrue> if <condition> else <whenIsFalse>

Lets's focus on the concept using an example:

import random

# random number to check is is greater or not than 10
number = random.randint(1, 20)
if number > 10:
  print(f'{number} is greater than 10')
else:
  print(f'{number} is less than 10')

That's a simple code, which could be re-written using the conditional expression as:

import random

# random number to check is is greater or not than 10
number = random.randint(1, 20)
print(f'{number} is greater than 10') if number > 10 else print(f'{number} is less than 10')

Well, that looks nice actually. A convenient way to write a ternary operator in one line. However, that's not a ternary-way in comparison with other languages. For that, there are some tricks that you can apply in Python but sadly, there are no a way to use the ?: symbols as operator.

Tricks to simulate the ternary operator

Using Tuples

All subsequent ways follow the same idea: create a collection with both options (greater and less) and using the selector operator [ ] to write the condition there. When the condition is True, it means the selection of position 1 of the collection, otherwise, is the condition is False then the selection is the position 0. This works based on the fact the True could be represented as 1 and False could be represented as 0.

Creating a tuple with both options:

tuple_cond = (f'{number} is less than 10', f'{number} is greater than 10')

and then, inside the operator [ ] we write the condition to evaluate number > 10:

tuple_cond[number > 10]

Also, this could be in just one line:

# when is True the selection is the position 1
(f'{number} is less than 10', f'{number} is greater than 10')[number > 10]

Using Dictionaries

This method is the same idea as before, just adding the keys as True and False:

{True: f'{number} is greater than 10', False: f'{number} is less than 10'}[number > 10]

Notice than there is no order because the dictionary uses the True and False keys to choose the result of the condition between [ ]

Using lambda functions

Maybe this is the most uncommon way to simulate the ternary operator. Nevertheless, it is still a path to follow:

(lambda: f'{number} is less than 10', lambda: f'{number} is greater than 10')[number > 10]()

Here, the order you should stick with; note the ( ) at the end of the sentence.

Then, you have some options to produce this conditional expression in Python, particularly I am not a fan of conditional expression for long lines, just for short ones. In case to utilize it, I prefer the dictionary way because the order is unimportant and it might reduce that kind of errors (who should be first?).


A curious note: Since its conception, Guido van Rossum never agreed with the addition of a ternary operator in Python. However, in 2005, he accepted in an email with the signature

It's still my language! :-)

From a geek to geeks


Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to The ecode.DEV repository
Great! Next, complete checkout for full access to The ecode.DEV repository
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.