Python Ternary Operator Explained [Easy Examples]

 

Introduction to Python ternary operators

Python ternary operators are also known as conditional expressions that evaluate something based on a condition being true or false. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact. In this tutorial, we will learn about python ternary, its syntax, and how it is different from if-else statements. We will also cover various ways to implement python ternary operators including tuples, dictionaries, lists, and lambda functions as well through different examples.

In a nutshell, this tutorial is going to contain different methods through which you can implement python ternary operators.

Advertisement

 

Getting started with Python ternary operators

As we already discussed that the python ternary operator is nothing but a one-line version of the if-else statement. It provides a way to write conditional statements in a single line, replacing the multi-line if-else syntax. In this section, we will cover the basic syntax of the python ternary operator and then will solve examples using the ternary operator and if-else statement as well.

 

Python if-else statement

An if-else statement in Python evaluates whether an expression is true or false. If a condition is true, then the if statement executes. Otherwise, the else statement executes. Let's have look at the simple example below, which uses Python if-else statement.

# declaring python variables
num1 = 4
num2= 5
# Python if statment
if num1==num2:
    print("Equla")
# Python else statement
else:
    print("Not equal")

Output:

Not equal

In the above example, will first check if the two numbers are equal or not. If they are equal then the if statement executes but if not then the else statement executes. Notice that the two numbers are not equal so the else statement has been executed. But notice that it took multiple lines to check the two numbers using if-else statement. In Python, we can apply the same logic in one line using the python ternary operator.

 

Syntax of Python ternary operator

The syntax of the Python ternary operator is very much similar to the if-else statement but unlike them, it is written in one line only. The syntax of the Python ternary operator looks like this:

<true_value> if <condition> else <false_value>

Here the condition is the boolean condition that evaluates to either true or false. The true_value is the return by the ternary operator if the condition evaluates to true and the false_value is returned by the ternary operator if the condition evaluates to false.

Advertisement

 

Python equivalent code with the ternary operator

In the example above, we have compared the equality of two numbers using if-else statements. Now, let us apply the same logic using Python ternary operator. See the example below:

# declaring python variables
num1 = 4
num2= 5
# Python ternary operator
print("Equal" if num1==num2 else "Not equal")

Output:

Not equal

It works in a similar way as the if-else statement. If the condition becomes true then the true_value ( Equal) will be executed, otherwise, it will execute the false_value( Not equal ). In the above case, the condition was not true, so the false_value is evaluated.

 

Implementation of Python ternary operator using tuple

Python tuples are a data structure that stores an ordered sequence of values. Tuples are immutable, this means we cannot change the values in a tuple. We can implement Python ternary operator using a tuple. In this section, we will first look at the syntax of using tuple for the Python ternary operator and then will solve an example as well.

 

Syntax of Python ternary operator using tuple

One way to implement ternary operation in Python is by using a tuple. This is a simple replacement for the if-else ternary operator. The simple syntax looks like this:

(false_value, true_value)[condition]

In this case, the false_value and true_value form the two elements of the tuple. And the conditional goes within the square bracket notation in place of an index. This works simply because the value of True is 1 and that of False is 0. If the condition evaluates to True, its value becomes 1 . Then the element at index 1 gets returned by the ternary expression. And if the condition evaluates to False, its value becomes 0. Then the element at index 0 gets returned.

 

Example of Python ternary operator using tuple

Now let us take an example of a python ternary operator using a tuple. See the example below which takes two numbers in a tuple and then checks which number is greater and prints it.

# declaring python variables
num1 = 4
num2= 5
# Python ternary operator using tuple
largest_number = (num2, num1)[num1>num2]
# printing the largest value
print(largest_number)

Output:

Advertisement
5

In the above Python program, first, the condition will be checked and if num1 is greater than num2 then it will return 1, and the element at index 1 will be stored in the largest_number variable. If num1 is less than or equal to num2 then the condition becomes false and it returns 0 then the element at index position 0 will be stored in the variable. In our example the condition was false so the element at position zero was stored in a variable. Let us take another simple example and print if the student has passed the exam or not using the python ternary operator.

# declaring python variable pass
Pass = True
# python ternary operator using tuple
result = ("You failed the exam!!", "You passed the exam!")[Pass]
# printing
print(result)

Output:

You passed the exam!

Notice that in the above example pass was True so the element at index position 1 was evaluated.

 

Implementation of Python ternary operator using dictionary

A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,). A colon (:) separates each key from its value. In this section, we will see how we can use a Python dictionary with a ternary operator. First, we will have a look at the basic syntax and then will solve examples.

 

Syntax of Python ternary operator using dictionary

The syntax of the python ternary operator using a dictionary is very similar to the tuple one. We just need to replace the tuple with a dictionary. See the syntax below:

{True: true_value, False: false_value}[condition]

In the above syntax, the true_value and false_value become the values of the keys True and False respectively. If the condition evaluates to True, the value corresponding to True gets returned. Else, the value corresponding to False gets returned. Now let us take an example and see how we can use a dictionary with Python ternary operator.

 

Example of Python ternary operator using dictionary

Now let us take an example and see how we can use Python ternary operator with a dictionary. See the python program below, which checks for the largest value.

# declaring python variables
num1 = 10
num2= 5
# python ternary operator using dictionary
result = {True: "num1 is larger", False: "num2 is larger"}[num1 > num2]
# printing
print(result)

Output:

Advertisement
num1 is larger

Notice that the condition in the above program was true, so the value associated with True in the dictionary was evaluated. Now let us take another example which checks if the student has passed the exam or not using the dictionary again. See the example below:

# declaring python variable pass
Pass = False
# python ternary operator using dictionary
result = {True: "You passed the exam!!", False: "You failed the exam!!"}[Pass]
# printing
print(result)

Output:

You failed the exam!!

Notice that the condition in the above example was false so the value of False was executed.

 

Implementation of Python ternary operator using lambda

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword. You can read more about the Python lambda function from the article on the Python lambda function. In this section, we will see how we can use the lambda function with the python ternary operator.

 

Syntax of Python ternary operator using lambda

The syntax of the Python ternary operatory which uses lambda is very much simple and straightforward. The lambda functions are followed by the conditions. See the syntax below:

(lambda : expression1, lambda: expression2)[condition]

Based on the condition, either expression1 or expression2 will be executed but not both.

 

Examples of Python ternary operator using lambda

Now let us take an example and see how we can use the lambda function with the python ternary operator. See the example below which checks the two numbers.

# declaring python variables
num1 = 10
num2= 5
# python ternary operator using lambda 
print((lambda : "num2 is larger", lambda: "num1 is larger")[num1 > num2]())

Output:

num1 is larger

Notice that the condition in the above program was true which returns 1 and the lambda function at position 1 inside a tuple was executed. Let us take another example and see how it works. See the example below:

# declaring python variable pass
Pass = False
# python ternary operator using lambda
print((lambda: "You failed the exam!!", lambda: "You passed the exam!!")[Pass]())

Output:

You failed the exam!!

The condition was false in the above example which returns 0 and the lambda function at position 0 was evaluated.

 

Implementation of Python ternary operator using a list

A list is an ordered and mutable Python container, being one of the most common data structures in Python. The square brackets ([]) are used to declare a list in python and the elements are separated by commas. In this section, we will see how we can use the list with the python ternary operator.

 

Syntax of Python ternary operator using a list

The syntax of using a list with a ternary operator is similar to other data structures that we have used. A list of elements is followed by a condition and based on the condition, an element from the list is executed. See the syntax below:

[false_value, true_value][condition]

If the condition is false the false_value will be executed because its position is 0 and if the condition becomes true then the true_value will be executed which is at index 1.

 

Examples of Python ternary operator using a list

Now let us take an example and see how we can use a list with the python ternary operator. We will take the same example and compare the two numbers. See the example below:

# declaring python variables
num1 = 10
num2= 5
# ternary operator using list
result = ["num2 is larger" , "num1 is larger"][num1 > num2]
# printing
print(result)

Output:

num1 is larger

Notice that the condition was true so it returns 1 and the element at the index 1 was executed. Now let us take another example and see if a student had passed the exam or not. See the example below:

# declaring python variable pass
Pass = False
# python ternary operator using list
result = ["You failed the exam!!", "You passed the exam!!"][Pass]
# printing
print(result)

Output:

You failed the exam!!

Notice that the condition was false which returns 0 and the value in the list at index position 0 was executed.

 

Summary

The Ternary Operator is a type of condition expression in the Python programming language that allows the developers to evaluate statements. The Ternary Operators execute an action depending on if that statement is either True or False. In this tutorial, we learned about the ternary operator and how we can use them instead of if-else statements. We learned various ways to implement the python ternary operator including tuple, list, dictionary, and lambda function along with different examples. To summarize, this tutorial contains various ways and examples to implement the ternary operator in python.

 

Further Reading

Python ternary operator
Python operators
Python conditional expressions

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment