The Python ternary operator is a powerful tool to improve your code’s readability. It is a short, concise way to execute code conditionally.
The Python ternary operator (or conditional expression) takes three operands. It can express the logic of an if/else statement in a single line of code with a format of [true result] if [condition] else [false result]. You use the ternary operator to write a shortened version of an if/else statement that includes the condition, an expression evaluated if the condition is true, and an expression evaluated if the condition is false.
This blog post will discuss using the Python ternary operator and when it is appropriate to use it. We will also provide examples of using the Python ternary operator in practice.
Is there A Python Ternary Operator?
Yes, Python has a ternary operator. The result of the ternary operator returns a value of one of the results depending on the outcome of the condition part of the expression.
What is the Python Ternary Operator?
In Python, the ternary operators help us write a conditional expression. It is a shorthand way of writing an if statement. The operator takes three operands and tests for a boolean condition. If the condition evaluates true, the operator returns the value of the first operand; else, the condition evaluates false and returns the value of the last operand.
The Python ternary conditional operator is a way of writing a shortened if statement. The syntax of the ternary operator is:
[on_true] if [expression] else [on_false]
If the expression evaluates to true, then on_true is executed; otherwise, on_false executes. For example:
How to Use the Python Ternary Operator
Demonstrate Ternary Operator – True Example
#Python ternary operator - True Condition
condition = True
print("True Result" if condition else "False Result") # Prints True Result
Ternary Operator – False Example
#Python ternary operator - False Condition
condition = False
print("True Result" if condition else "False Result") # Prints False Result
In the first example, the return value is “True Result” if the condition variable is True. Otherwise, it is a “False Result.” Therefore, when we print out the result variable, it will print out “True Result.”
In the second example, the condition variable is assigned False, and thus the ternary operator prints out the last operand, “False Result.”
You can also use nested ternary operators if you need to test for more than one condition. In general, though, it is best to avoid using nested ternary operators as they can make your code difficult to read.
Using Ternary Operator with Method Calls
You can also use the ternary operator to make method calls. The following example shows how to use the ternary operator with a method call.
True Example
#Python ternary operators method calls - True Condition
def true_result():
return "True Result"
def false_result():
return "False Result"
condition = True
print(true_result() if condition else false_result()) # Prints True Result
In this example, in place of returning the string result directly, we make a method call for the true and false statement, and the result is the same.
Using the Ternary Operator with Python Tuples
In Python, you may use a tuple to express the ternary operator more succinctly. To see how this syntax works, let’s go back to the basic ternary operator format:
If the condition is True
>>> one = 1
>>> two = 2
>>> one if one > 0 else two
>>> 1
If the condition is False
>>> one = -1
>>> two = 2
>>> one if one > 0 else two
>>> 2
Now let’s see how to write this expression using Python tuples:
If the condition is True
>>> one = 1
>>> two = 2
>>> (two, one)[one > 0]
>>> 1
If the condition is False
>>> one = -1
>>> two = 2
>>> (two, one)[one > 0]
>>> 2
The ternary operator with a tuple produces the same result as the standard ternary operator. But why? It may be perplexing when you see this tuple ternary operator first. To comprehend how it works, you must understand how Python boolean values True and False are represented as integers.
Using the built-in int () class, let’s use the Python shell to convert True and False to integers using the built-in int() class.
>>> int(True)
>>> 1
>>> int(False)
>>> 0
The value of True is 1, while the value of False is 0.
We can take advantage of the output of the condition as an index to get at one of the items in the tuple.
We test if the result is equal to 0 (False); if so, we access the first item of the tuple alternatively; if not, we’ll use the second. The tuple ordering also explains why we reverse the items in our example.
(two, one)[one > 0]
Assign the Result of the Ternary Operator to a Variable
You can also assign the result of a ternary operator to a variable. The following example shows how to do this.
#Python ternary operator assigns to variable - True Condition
condition = True
result = "True Result" if condition else "False Result"
print(result) # Prints True Result
As you can see, you can use the same syntax as before, but you need to add the variable name that you want to assign the result. In this case, we gave it to the result variable.
Using a Nested Ternary Operator
You can use a nested ternary operator if you need to test for more than one condition. In general, though, it is best to avoid using nested ternary operators as they can make your code difficult to read.
The following example shows how to use a nested ternary operator.
Nested Ternary Operators – True
#Demonstrate nested ternary operator
condition1 = True
condition2 = True
result = "True Result" if condition1 else ("False Result" if condition2 else "Default Result")
print(result) # Prints True Result
You can see that you can use the same syntax as before; in the second statement of the first expression, we have another ternary operator. As you can see, the expression is already getting complicated. Compare reading the above to the same if/else statement.
Nested If/Else
#Demonstrate uncomplicated if/else code instead of nested ternary operators
condition1 = True
condition2 = True
if condition1:
return 'True Result'
elif condition2:
return 'False Result'
else:
return 'Default Result'
When to Use Python Ternary Operators
You use the Python ternary operator to execute code conditionally. However, there are other use cases for the ternary operator as well. For example, you can also use it for assignment or return values from a function.
While the ternary operator can be helpful in some situations, it is essential to use it sparingly. Generally, the ternary operator’s code is more challenging to read and understand than equivalent code written using an if/else statement.
Furthermore, it would be best if you did not use the ternary operator for complex conditions; nested ternary operators can quickly become confusing and difficult to debug. When in doubt, it is usually best to stick with a simple if/else statement.
Additional Python Ternary Operators
There is an alternative ternary operator in Python called the shorthand ternary. It is slightly shorter than the standard ternary operator.
The shorthand ternary has the alternative syntax of [condition] or [false result].
Let us imagine we have a scenario where we want to detect the existence of a filename in our program. Furthermore, we want to return a message if we found the filename on the system or not.
Short Hand Ternary Operator – True Result
>>> file_result_message = "File Found"
>>> message = file_result_message or "File Not Found"
>>> print(message) # Prints File Found
Short Hand Ternary Operator – False Result
>>> file_result_message = None
>>> message = file_result_message or "File Not Found"
>>> print(message) # Prints File Not Found
Is the Python Ternary Operator Faster than If?
You can use the Python ternary operator to simplify code that would otherwise require an if-else statement. However, some people claim that the Python ternary operator is slower than an if-else statement. So, which is faster?
Let’s write a simple program using the timeit module to test it out.
Testing How Fast the Ternary Operator Evaluates vs. if/else
#Testing how fast the ternary operators evaluates vs. if/else statement
import timeit
def ternary_operator(x):
return x if x > 0 else -x
def if_else_operator(x):
if x > 0:
return x
else:
return -x
ternary_time = 0
for_time = 0
iterations = 1001
for x in range(iterations):
ternary_time += timeit.timeit('ternary_operator(1)', setup='from __main__ import ternary_operator')
for_time += timeit.timeit('if_else_operator(1)', setup='from __main__ import if_else_operator')
print('Ternary Average: ' + str(ternary_time / iterations))
print('For Average: ' + str(for_time / iterations))
In the above code, we have two methods that run the Python ternary and the if/else. We run 1001 iterations of the test and average it out.
The result is that the ternary operator evaluates slightly slower.
Why Is It Called Ternary Operator?
The term “ternary” comes from the Latin word “tres,” which means three. So, the Python ternary operator is called ternary because it takes three operands.
Wrapping Up
In conclusion, the Python ternary operator is a powerful tool that you can use to improve your code’s readability and make your code compact. It is a short, concise way to build conditional expressions. The Python ternary operator (or conditional expression) takes three operands and can express the logic of an if/else statement in a single line of code. While it is essential to use the ternary operator sparingly, as it can make your code difficult to read, it can be helpful in some situations.
The Python ternary operator is just as fast as an if/else statement. So, if you’re looking for a way to simplify your Python programming, the ternary operator is a good option. Thanks for reading! We hope this article has been helpful. Happy coding!