Python Ternary Operator

Learn to make use of the Python Ternary Operator to evaluate expressions based on conditions in a single line of code with the help of illustrative examples.

Python Ternary Operator

In Python, when you have to evaluate a boolean expression and then according to the result of the expression (whether True or False) when you’ve to execute something or print something, you might often be making use of Python if-else statements. But even writing a simple if-else statement might take a few lines of code. With the help of the Ternary operator, you can do the same thing in Python as making use of the If-else statement. It’s just that with the Ternary Operator the length of code is reduced from multiple lines into just a single line. The Ternary Operators are available since Python Version 2.5. It’s actually the use of the If-else statement in an innovative way.

Syntax

Given below is the self-explanatory syntax of the Python Ternary Operator.

In place of {result_if_True}, you will type the Python Code to be executed if the expression result is True and the code to be executed if the condition is False has to be replaced by {result_if_False}.

Examples

Let’s understand the concept of Python Ternary Operator with the help of examples.

Example 1. Simplest Usage

In the following example, we’re just checking if the variable x is less than y or not.

#Python Ternary Operator Example 1
x = 5
y = 8

print("x is small") if x < y else print("y is small")

x = 12
y = 5

print("x is small") if x < y else print("y is small")

In the above Python Code, I’ve first defined the values of the variables x and y to be 5 and 8 respectively. Then I used the Ternary operator to print whether x is small or y is small according to condition x < y. Then after, I changed the values of the variables variables x and y to be 12 and 5 respectively.

Python Ternary Operator Example 1

Hence, in the output screenshot, you can clearly see first it prints out that x is small for the first case and then for the second case, it prints out, y is small.

This is the first and basic approach to make use of the Ternary operator in Python. But there are several other ways to utilize this operator as well, which you’ll find out in the other examples given below.

Example 2. Ternary Method For Collections (Tuple, Dictionary & Lambda)

This method follows a simple approach. The collections like Tuple & Dictionary will contain two items. The first item will be selected for the result if the condition so defined is True and the second item will be selected for the result if the condition so defined is False.

#Python Ternary Operator Example 1
x = 50
y = 100

#Syntax
#print(({Result_if_True},{Result_if_False})[{Condition}])
#y > x, True, Hence, x is printed.
print((x, y)[y > x])

#x > y, False, Hence, "y is greater than x" is printed
print(("x is greater than y", "y is greater than x")[y > x])

#Similarly For Dictionary
result_dict = {True: "Condition is True", False: "Condition is False"}
print(result_dict[x > y])
print(result_dict[x == y])
print(result_dict[y > x])

#You can also make use of the lambda function for the same purpose
print((lambda: x, lambda: y)[x < y]())

Here also, we’ve defined the variables x and y to be 50 and 100 respectively. Then I created a list with only two items and these two items are the variables x and y. Then in square brackets, I’ve written the condition y > x right after the tuple. So, now as the condition is true because 100 is greater than 50, hence the first item of the tuple will be returned which is being printed to the console with the help of the print statement.

Similarly, in the next case, we’re returning Strings instead of number variables themselves using the same logic. The logic also remains the same with the Dictionary. We’ve defined two keys in the dictionary, True and False. The value that is held by the key True will be returned if the condition is True and the value held by the key False will be returned if the condition is False. Here we’re using the same dictionary to check for different conditions.

In the end, I’ve also illustrated that you can also make use of lambda to do the same, it’s just that you’ve to apply the condition as a method on it as clearly shown in the following screenshot and the code above.

Python Ternary Operator Example 2

Note. There is an advantage to making use of the lambda method over the tuple and dictionary methods. The reason being in lambda method, only one expression is evaluated while in the tuple and dictionary both the True and False values are evaluated. In case, your resultant expressions are complex, using the lambda function can save you some computing memory.

Example 3. Ternary Operator in Case of Nested Conditions

Till now, we’ve seen the usage of the Ternary Operator just for a single condition. But you can make use of this operator for multiple conditions as well. This is exactly what is illustrated in the following example.

#Python Ternary Operator Example 3
x = 15
y = 25
result = "x is equal to y" if x == y else "x is greater than y" if x > y else "y is greater than x"
print(result)

x = 13
y = 11
result = "x is equal to y" if x == y else "x is greater than y" if x > y else "y is greater than x"
print(result)

x = 5
y = 5
result = "x is equal to y" if x == y else "x is greater than y" if x > y else "y is greater than x"
print(result)

The above code is similar to writing the following if-else statement.

#Python Ternary Operator Example 3
x = 15
y = 25
if x == y:
    print("x is equal to y")
elif x > y:
    print("x is greater than y")
else:
    print("y is greater than x")

Python Ternary Operator (Nested Conditions) Example 3

Example 4. For Python Version 2.4 or less.

In case, you want a similar feature as the Ternary operators in Python Version 2.4 or less, you can make use of the and & or condition to achieve the same. The following example illustrates how you can do this in the earlier versions of Python that do not support Ternary Operators.

#Python Ternary Operators Example 4
#In case Python Version <= 2.4

x = 30
y = 40

result = x < y and "x is small" or "y is small"
print(result)

x = 50
y = 35

result = x < y and "x is small" or "y is small"
print(result)

The syntax that the above code follows is given below.

result = {condition_or_expression} and {result_if_True} or {result_if_False}

Note. There is a minor disadvantage to making use of this thing over the ternary operators available in Python Version 2.5 and above. The {result_if_true} should not be 0 or False, otherwise, you might not get the right answer.

Python Ternary Operator For Version 2.4 Or Earlier Example

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *