Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python Ternary If Else
2.1.
Python
3.
Ternary Operator in Nested If Else
3.1.
Python
4.
Ternary Operator Using Python Tuple
4.1.
Python
5.
Ternary Operator Using Python Dictionary
5.1.
Python
6.
Ternary Operator Using Python Lambda
6.1.
Python
7.
Ternary Operator with Print Function
7.1.
Python
8.
Limitations of Python Ternary Operator
8.1.
Python
9.
Frequently Asked Questions
9.1.
Can I use the ternary operator with all data types in Python?
9.2.
Is the ternary operator faster than using an if-else statement?
9.3.
When should I avoid using the ternary operator?
10.
Conclusion
Last Updated: May 21, 2024
Easy

Python Ternary Operator

Author Ravi Khorwal
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Python is a versatile programming language that offers many ways to write concise & efficient code. One such feature is the ternary operator, which allows you to write conditional statements in a single line. It's a shorthand way of writing an if-else statement, making your code more readable & compact. 

Python Ternary Operator

In this article, we'll talk abouy the Python ternary operator in detail, including its syntax, usage, & various examples. We'll also cover some advanced topics like using the ternary operator with nested if-else statements, tuples, dictionaries, & lambda functions.

Python Ternary If Else

The Python ternary operator provides a compact way to assign values based on conditions. It's structured as: value_if_true if condition else value_if_false. This makes your code shorter & often easier to understand than using a full if-else statement. For example, to quickly determine if a number is even or odd, you could write:

  • Python

Python

num = 8

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

print(result)

Output

Even


This code checks if the number (num) is divisible by 2. If true, result is set to "Even"; otherwise, it's set to "Odd". It's a straightforward use of the ternary operator that replaces several lines of a typical if-else block.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Ternary Operator in Nested If Else

Using the ternary operator within nested conditions allows for even more streamlined decision-making in your Python code. Let's say we need to classify a temperature reading as "Hot", "Warm", "Cool", or "Cold". We can efficiently achieve this with nested ternaries:

  • Python

Python

temperature = 55

description = (

   "Hot" if temperature > 85 else

   "Warm" if temperature > 60 else

   "Cool" if temperature > 40 else

   "Cold"

)

print(description)

Output

Cool


In this example, the program evaluates multiple conditions in a single expression. It checks the temperature, & assigns a string based on its value. This approach is not only tidy but reduces the complexity seen with multiple nested if-else statements.

Ternary Operator Using Python Tuple

The ternary operator can also be cleverly combined with Python tuples to decide between two outcomes. This method is particularly useful when you want to choose between two values based on a condition that evaluates to True (0) or False (1). Here’s how you can use a tuple with the ternary operator:

  • Python

Python

score = 67

result = ("Fail", "Pass")[score >= 60]

print(result)

Output

Pass


In this code, the tuple ("Fail", "Pass") holds possible outcomes. The condition score >= 60 evaluates to True or False, where True corresponds to 1 and False to 0. Based on this, the tuple returns "Pass" if the score is 60 or above, and "Fail" otherwise. This method is a compact and efficient way to handle simple binary decisions.

Ternary Operator Using Python Dictionary

Utilizing Python dictionaries with the ternary operator offers a robust way to manage multiple conditions & outcomes efficiently. This approach is particularly effective when you have several potential results based on varying conditions. Here’s an example of how to implement this:

  • Python

Python

age = 25

person_type = {

   True: "Adult",

   False: "Minor"

}[age >= 18]

print(person_type)

Output

Adult


In this example, the dictionary {True: "Adult", False: "Minor"} is used to determine the type of person based on their age. The condition age >= 18 evaluates to either True or False, & the dictionary returns "Adult" if the person is 18 or older, & "Minor" otherwise. This method streamlines code that would otherwise require multiple if-else statements.

Ternary Operator Using Python Lambda

Lambda functions in Python provide a concise way to execute small functions in a single line, and when paired with the ternary operator, they become even more powerful for quick decision-making processes. This combination is ideal for situations where you need to execute simple functions based on a condition. Here's how you can integrate a lambda with the ternary operator:

  • Python

Python

calculate_grade = lambda score: "Pass" if score >= 50 else "Fail"

grade = calculate_grade(68)

print(grade)

Output

Pass


In this code snippet, the lambda function calculate_grade takes one parameter, score, and immediately returns "Pass" if the score is 50 or higher, or "Fail" if it is lower. This use of the ternary operator within a lambda function simplifies the function's structure, making your code more readable and efficient.

Ternary Operator with Print Function

Incorporating the ternary operator directly into a print function simplifies the process of outputting results based on a condition. This technique can make scripts more concise & reduce the need for additional lines of code to handle conditional logic. Here’s how you can effectively use the ternary operator within a print statement:

  • Python

Python

temperature = 72

print("It's warm" if 70 <= temperature < 85 else "It's not warm")

 

Output

It's not warm


This example demonstrates the use of the ternary operator to check the temperature & immediately print "It's warm" if the condition (70 <= temperature < 85) is met, & "It's not warm" otherwise. This is a practical way to output information based on a condition directly, making the code cleaner & more straightforward.

Limitations of Python Ternary Operator

While the Python ternary operator is a powerful tool for simplifying code, it has its limitations that programmers should be aware of. The most significant limitation is its suitability for simple, concise conditions. When conditions become complex or involve multiple steps, using the ternary operator can make the code less readable & harder to understand. For example:

  • Python

Python

x = 5

y = 10

result = "Both are equal" if x == y else "Not equal" if x < y else "X is greater"

print(result)

Output

Not equal


In cases like this, while technically possible, nesting multiple ternary operators can lead to code that is difficult to follow. It's generally recommended to use traditional if-else statements for more complex decision-making to maintain clarity & ensure that your code is easy for others to read and maintain.

Another limitation is the lack of support for executing multiple statements within each condition. Each part of the ternary expression must be an expression that returns a value, not a series of actions (which would be possible in a regular if-else statement).

Frequently Asked Questions

Can I use the ternary operator with all data types in Python?

Yes, the ternary operator works with any data type that can be evaluated in a conditional expression. Whether you're dealing with numbers, strings, lists, or any other data type, you can use it to assign values based on a condition.

Is the ternary operator faster than using an if-else statement?

The performance difference between the ternary operator and an if-else statement is generally negligible. The choice between them should be based on readability & the complexity of the condition rather than performance.

When should I avoid using the ternary operator?

Avoid using the ternary operator in situations where the condition or the expressions are too complex. If using it complicates the readability of your code, it's better to use a regular if-else statement.

Conclusion

In this article, we have learned how the Python ternary operator can simplify conditional statements in your code, making it more concise and readable. We saw its basic usage and several innovative ways to integrate it with other Python features like tuples, dictionaries, lambda functions, and even within print statements. We also discussed the limitations of the ternary operator, highlighting scenarios where a traditional if-else approach might be preferable to maintain clarity. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Switch Case in Python
Next article
Indented Block In Python
Live masterclass