In this short tutorial, let us look at how we can write code using the Python ternary operator. One can make their Python code more concise using the ternary operator.
Table of contents - Python ternary operators
- What are ternary operators in Python?
- Syntax
- Simple example of Python ternary operator in a program
- Python ternary operator with Tuples, Dictionary and Lambda
- Closing thoughts
What are ternary operators in Python?
Here, Python’s ternary or conditional operators are operators that evaluate something based on a condition being true or false. They are also known as conditional expressions. To further simplify it, ternary operators can be thought of as one-line versions of the if-else statements.
Syntax
As the name suggests, Python’s ternary operators need three operands to run. The three operands are:
- condition: A boolean expression that needs to evaluate whether true or false.
- val_true: A value that is to be assigned if the condition evaluates to be true.
- val_false: A value that is to be assigned if the condition evaluates to be false.
When it’s all put together this is how it should look like:
some_var = val_true if [condition] else val_false
The variable some_var that you see on the left side of the equal-to sign “=” (assignment operator) will be assigned either one of the following:
- val_true if the boolean expression evaluates to be true. Or
- val_false if the boolean expression evaluates to be false.
Simple example of the Python ternary operator in a program
Let’s write a simple Python program that helps us understand the ternary operator’s usage. To understand the difference between the Python ternary operator and the if-else statement method, let's first write the program using the if-else statement.
The program using the "if-else" method:
your_age = input('Enter your age to check if you are eligible to legally drive or not:')
if int(your_age) >= 18:
driving_permit = “Yes, you can drive!”
else:
driving_permit = “Sorry, you can’t drive yet!”
print(f"The Result - {driving_permit}")
And here is the output if 20 is the input:
Enter your age to check if you are eligible to legally drive or not: 20
The Result - Yes, you can drive!
In this example, the if-else statement assigns “Yes, you can drive!” to the driving_permit variable if the age entered is greater than or equal to 18. Otherwise, it assigns Sorry, you can’t drive yet!” to driving_permit.
Now, to make this program a lot more concise, we can make use of the syntax of the ternary expression.
The program using the ternary operator method
your_age = input('Enter your age to check if you are eligible to legally drive or not:')
driving_permit = “Yes, you can drive!” if int(your_age) >= 18 else “Sorry, you can’t drive yet!”
print(f"The Result - {driving_permit}")
In this statement, the left side of the assignment operator (=) is the variable driving_permit. The ternary operator evaluates the condition which is if int(your_age) >= 18. If the result is true, then it returns the val_true, which in this case is “Yes, you can drive!”. Else it returns val_false, which is Sorry, you can’t drive yet!”
Python ternary operator with Tuples, Dictionary and Lambda
As we now have an understanding of how Python’s ternary operator works, let’s see how it applies with Tuples, Dictionary and Lambda. Before that, let’s begin with a simple program on finding the greatest of 2 numbers. It helps with having a clear picture of what we want to accomplish when we apply the ternary method with Python’s Tuples, Dictionary and Lambda function.
Sample program of Python ternary operator.
Here is a simple Python program where we find the greatest of 2 numbers using the ternary operator method.
Input:
# A code snippet to demonstrate the Python ternary operator
# Finding the greatest of 2 numbers
x, y = 20, 40
max = x if x > y else y
print(max )
Output:
40
If [x>y] is true it returns 1, so the element with 1 index will be printed. Otherwise if [x>y] is false it will return 0, so the element with 0 index will be printed.
Python ternary operator with Tuples
Let’s now see how ternary conditions are used with Tuples. The syntax to be considered during the usage of the ternary operator with Tuples is (if_check_is_false, if_check_is_true)[check]
Input:
# A simple program to demonstrate Python ternary operator with Tuples
x, y = 20, 40
print( (y, x) [x > y] )
Output:
40
Python ternary operator with Dictionary
Let’s now see how ternary conditions are used with the Dictionary data structure.
Input:
# A simple program to demonstrate Python ternary operator with Dictionary
x, y = 20, 40
print({True: x, False: y} [x > y])
Output:
40
In this case, if [x > y] is True then the value of the True key will be printed. Else if [x>y] is False then the value of the False key will be printed
Python ternary operator with the Lambda function
Interestingly, implementing the ternary operator with the Lambda function is more efficient than the other two methods. This is because with Lambda we are assured that only one expression will be evaluated. But in the instance of Tuple or Dictionary, both the expressions are evaluated.
Input:
# A simple program to demonstrate Python ternary operator with Lambda
x, y = 20, 40
print((lambda: y, lambda: x)[x > y]())
Output:
40
Closing thoughts
The Python ternary operator is a concise and simple way of implementing if-else statements. It first evaluates the given condition, then returns a specific value depending on whether that condition turns out to be True or False.
But we need to note that the ternary operator cannot always be used. For example, if you want to test for multiple expressions, you should write out a full if-else statement as usual.
Top comments (0)