Ternary Operator in Python – What? How? Why?

by | Python

In the world of programming, having the ability to simplify code is valuable for both code readability and efficiency. One tool at your disposal for doing this in Python is the ternary operator.

The Python ternary operator (or conditional expression) allows you to evaluate statements based on whether a given condition is true or false, all in a single line of code. It can effectively replace a multiline if-else statement making your code more compact.

As we explore the potential of Python ternary operators, you’ll find that they can be very useful for optimizing your programs. Whether it’s to simplify decision-making logic or streamline your code, using Python ternary operators effectively can make your code much easier to read and understand.

So, let’s take a look under the hood and see what they are all about!

Ternary Operator in Python

What is a Python Ternary Operator?

Python Ternary operators offer a concise way to evaluate a statement based on whether a condition is true or false, making your code compact and easier to read. Some people also call them conditional expressions or conditional operators.

Basic Syntax

The ternary operator was introduced in Python 2.5 and has a simple structure consisting of three operands:

#demonstrate python ternary operator syntax

result = value_if_true if condition else value_if_false

This syntax consists of three main parts:

  1. The condition: This is a boolean expression evaluated as either true or false, a

  2. value_if_true: The value that gets returned if the boolean expression is true.

  3. value_if_false: The value that gets returned if the boolean expression is false.

Common Use Cases

Ternary operators or conditional expressions are often used to simplify short if-else statements in your code. Here are a few examples to illustrate how you can apply a Python ternary operator:

Example 1: Assigning a value based on a condition

 age = 25
category = "adult" if age >= 18 else "minor"

In this example, the Python ternary operator assigns the value “adult” to the variable category if the age is greater than or equal to 18, and “minor” otherwise.

Assuming we opted to use an if-else statement instead of a Python ternary operator, it would look something like this:

age = 25

if age > 18:
   category = "Adult"
   category = "Minor"

In this case, we can see that using a ternary operator makes the code much more compact and easy to read.

Example 2: Selecting the smallest of two numbers

a = 10
b = 15

smallest = a if a < b else b

Here, the ternary conditional operator helps you determine the smallest of two numbers by returning the smaller value between a and b.

Example 3: Assigning the minimum value of two variables:

num1 = 10
num2 = 20

min_num = num1 if num1 < num2 else num2

The output for this example will be 10, as the ternary operator evaluates the condition and returns the smaller value.

Example 4: Finding if a number is even or odd:

num = 5

result = "Even" if num % 2 == 0 else "Odd" 

The output for this example will be Odd, as the condition evaluates to False, and the ternary operator returns the appropriate result.

These examples demonstrate how a Python ternary operator can make your code more concise and easier to read. By using the basic syntax and understanding common use cases, you can effectively incorporate a ternary operator into your Python code.

In more practical applications, you can use it in conjunction with a loop to check, evaluate or perform operations on data.

For more efficient data handling, you can check out this video on How To Handle Missing Data In Python With Interpolation.

How to Use The Python Ternary Operator

The normal ternary operator if-else syntax is just one of many ways we can implement a Python ternary operator. We can also implement it by using common data structures like Python dictionaries, tuples, and lists.

Let’s look at some of these methods:

Dictionary Mapping

You can emulate a Python ternary operator with dictionary mapping to store the results for different conditions. It can be useful when you have a finite set of conditions and corresponding results.

Here’s an example using dictionary mapping to check if a number is even or odd:

#Implement python ternary operator with dictionary mapping

number = 7
result = {True: "Even", False: "Odd"}

is_even = result[number % 2 == 0]

The program above will return “Odd” since the boolean expression in the brackets evaluates to False.

Using Tuples

Python tuples are an ordered, immutable data structure that you can use to implement ternary operators. Basically, the tuple ternary operator has a syntax of:

(condition_is_false, condition_is_true)[condition]

The condition evaluates to either True or False which in Python are equal to the integers 1 and o respectively.

So, the tuple returns whichever element matches the resulting index. For example, if the condition evaluates to True which is 1, the code return condition_is true.

Otherwise, it evaluates to False which is 0, and the tuple returns condition_is_false. Here’s an example below:

#Implement ternary operator with tuples

c = False
result = ('a', 'b')[c]

The tuple will store the value ‘a‘ in the variable result since the condition evaluates to False. Most developers do not like using this format for ternary operators as it can be a little confusing, which defeats the purpose.

Lambda Functions

Lambda functions are anonymous single-line functions that you can use as an alternative to ternary operators. They allow you to perform simple calculations and return a result based on a given condition.

Here’s an example of using a lambda function to find the maximum of two numbers:

#implement python ternary operator with lambda functions

a, b = 10, 20
max_value = (lambda: a, lambda: b)[a < b]()

The lambda function returns a if the condition evaluates to True. Otherwise, it returns b.

What is a Nested Ternary Operator?

A nested ternary operator is a conditional expression with two or more boolean expressions. You can create this by chaining two or more boolean conditions together to check multiple conditions.

We can use these types of ternary operators to model “elif” statements and nested if-else blocks.

Let’s look at an example of a nested Python ternary operator.

age = 21

#Normal elif statement
if age< 21:
elif age< 25:
   print ('young adult')

#elif statement as a ternary operator
print('Child') if age < 18 else print('Young adult') if age <21 else print ('Old Person')

#Output: 'Young Adult'

You can add brackets to the Python ternary operator if you want to mimic a nested if-else statement. However, this is not good practice as the ternary operator can become very long and unreadable.

In cases like this, you’re better off using a standard if-else block in your code.

What Are The Advantages of The Python Ternary Operator?

There are many advantages you get from using the Python ternary operator in your code. Some of these advantages include:

Code Readability and Brevity

Using the Python ternary operator can make your code more concise, allowing you to write conditional expressions in a single line.

This is especially helpful when dealing with simple and straightforward conditions. Your code can be more readable and easier to understand, as it reduces the need for multiple lines of if-else statements.

Performance Considerations

Although the ternary operator can lead to more compact code, its impact on performance is usually minimal. Python’s interpreter is designed to optimize code execution, meaning that both the ternary operator and if-else statements generally have similar performance characteristics.

When writing Python code, prioritize readability and maintainability over performance, unless you are working with performance-critical applications.

Remember that different situations call for different approaches. Sometimes, using the ternary operator is beneficial, while in other cases, sticking to traditional if-else statements may be more suitable.

Disadvantages of the Python Ternary Operator

Ternary operators are great for simplifying your code and making them compact. However, using them may have some drawbacks.

Here are some of these drawbacks:

Nested Ternary Operators Can Get Complex

In some cases, the ternary operator may make the code less readable, particularly when using complex or nested conditions. In these situations, incorporating conventional if-else statements may be more appropriate to maintain code clarity.

This is especially true when you’re trying to replace a nested if-else statement with a ternary operator. It seldom results in clean code.

Each Operand is an Expression

All the operands or return values in a Python ternary operator are expressions, not statements. Trying to use an assignment statement inside the ternary operator’s syntax will lead to a syntax error.

You can check out an example of this in the code below.

'Adult' if True else x = 44

As you can see below, it results in a syntax error. In cases like this, you should use an if-else block instead of a conditional operator.

Syntx Error from Python Ternary Operator

Best Practices and Tips

When using the ternary operator in Python, there are some best practices and tips to help you write clean, efficient, and readable code.

Firstly, ensure that your conditional expression is short and concise. Long and complex conditions might make it difficult to understand the logic behind the ternary operator.

If you find yourself facing a complex condition, it might be better to use a regular if-else statement instead.

#demonstrate nested ternary operator
# Good example 
result = "positive" if number >= 0 else "negative" 

# Bad example 
result = (a + b if (x > 10 and y > 20) else c + d) if (z > 30 and p > 40) else ...

Secondly, avoid nesting multiple ternary operators, which can lead to confusing and unreadable code. Like with complex conditions, consider using an if-else statement for more readability.

# Good example 

x = A if condition1 else B if condition2 else C 

# Bad example 
x = A if condition1 else (B if condition2 else (C if condition3 else ...)) 

Lastly, be mindful of the appropriate use cases for the ternary operator. It is most suitable for simple, single-line assignments where the condition and the outcome are both easy to understand.

If your code involves more complex logic, loops, or multiple assignments, it’s better to stick to traditional if-else statements.

FAQs on Python Ternary Operators

Here are some questions new programmers usually ask us about ternary operators:

How do you use the ternary operator in a return statement in Python?

You can use a Python ternary operator in a function’s return statement. All you have to do is to add it to the return statement.

Here is an example:

#program to check cheese age

def is_legal(age):
  return 'legal' if age > 18 else 'Not legal'

Is a ternary operator faster than an if-else statement in Python?

No, both of them have similar performance characteristics. A ternary operator and an if-else statement both have an O(1) time complexity.

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts