Open In App

Ternary Operator in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, Ternary Operator determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.

It’s convenient when we want to avoid writing multiple lines for a simple if-else condition. Like in simple if-else, the first option, the true_value will be executed when the condition provided in the expression is True. If the condition returns False, then false_value will be executed.

Syntax: true_value if condition else false_value

The ternary operator can be used in various ways. Let us see a few different examples to use Ternary Operators in Python:

Python Ternary If Else

The simplest way to use a Python ternary operator is when we have a simple if else condition, that is, either of the two conditions is True and the other is False.

Example: In this code we will compare and find the minimum number from the given two numbers using the Ternary Operators in Python and storing the result in a variable name ‘min’. If ‘a‘ is minimum, the value of ‘a‘ will be printed, else the value of ‘b‘ will be printed.

Python
# Program to demonstrate ternary operator
a = 10
b = 20

# python ternary operator
min = "a is minimum" if a < b else "b is minimum"

print(min)

Output:

a is minimum

Ternary Operator in Nested If else

The ternary operator can also be used in Python nested if-else statement. the syntax for the same is as follows:

Syntax: true_value  if condition1 else (true_value if condition2  else false_value)

Example: In this example, we are using a nested if-else to demonstrate ternary operator. If ‘a’ and ‘b‘ are equal then we will print ‘a and b are equal’ and else if ‘a’ is greater then ‘b’ then we will print ‘a is greater than b’ otherwise ‘b is greater than a’.

Python
# Python program to demonstrate nested ternary operator
a = 10
b = 20

print("Both are equal" if a == b else "a is greater"
      if a > b else "b is greater")

Output:

b is greater

Ternary Operator using Python Tuple

The ternary operator can also be written by using Python tuples. In this case we declare the False and True values inside a tuple at index 0 and 1 respectively. Based on the condition, if the result is False, that is 0 the value at index 0 gets executed. If the condition results in True, the value at index 1 of the tuple is executed.

Syntax: (false_value, true_value) [condition]

Example: In this example, we will compare and print the minimum value, where the the values to be executed are declared inside the tuple.

Python
# Program to demonstrate ternary operator
a = 10
b = 20

# python ternary operator usinf tuple
print(("b is minimum", "a is minimum") [a < b])

Output:

a is minimum

Ternary Operator using Python Dictionary

The Python ternary operator can also be written by using Python dictionary. In this case we use True and False keywords as the dictionary keys and provide them with a value to be executed based on the condition’s result.

Syntax: (True: true_value, False: false_value) [condition]

Example: In this example, we are using Dictionary to demonstrate ternary operator, where we have given a True and a False values to dictionary keys, that will be executed based on condition’s result.

Python
# Python program to demonstrate ternary operator
a, b = 10, 20

print({True: "a is minimum", False: "b is minimum"} [a < b])

Output:

a is minimum

Ternary Operator using Python Lambda

In Python, lambda functions are used when we have only one expression to evaluate. Hence using the teranery operator with lambda makes it quite simple and easy. It works exactly like the tuple. That is we declare the False and True values at index 0 and 1 respectively.

Syntax: (lambda: false_value, lambda: true_value) [condition] ()

Example: In this example, we are using Lambda to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.

Python
# Python program to demonstrate ternary operator
a = 10
b = 20

print((lambda: "b is minimum", lambda: "a is minimum")[a < b]())

Output:

a is minimum

Ternary Operator with Print Function

The ternary operator can also be directly used with the Python print statement. Its syntax is a s follows:

Syntax: print(true_value) if (condition) print(false_value)

Example: In this example, we are finding the minimum number among two numbers using Python ternary operator with print statement.

Python
a = 10
b = 20

# ternary operator with print statement
print(a,"is minimum") if (a < b) else print(b,"is minimum")

Output:

10 is minimum

Limitations of Python Ternary Operator

Python ternary operator is used to write concise conditional statements but it too have some limitations.

  • Readability: Ternary operator can make simple conditional expressions more concise, it can also reduce the readability of your code, especially if the condition and the expressions are complex.
  • Potential for Error: Incorrect placement of parentheses, missing colons, or incorrect order of expressions can lead to syntax errors that might be harder to spot.
  • Debugging: When debugging, it might be harder to inspect the values of variables involved in a complex ternary expression.
  • Maintenance and Extensibility: Complex ternary expressions might become harder to maintain and extend especially when the codebase grows.
  • Can’t use assignment statements: Each operand of the Python ternary operator is an expression, not a statement, that means we can’t use assignment statements inside any of them. Otherwise, the program will throw an error.

Example:

Python
3 if True else x=6

Output:

File "Solution.py", line 1
3 if True else x=6
^
SyntaxError: can't assign to conditional expression

Ternary Operator in Python – FAQs

What does ternary operator do in Python?

The ternary operator in Python is a one-liner conditional expression that assigns a value based on a condition. It is written as value_if_true if condition else value_if_false.

a = 5
b = 10
max_value = a if a > b else b # max_value will be 10

What is ternary in dictionary Python?

A ternary operator can be used within a dictionary to set values based on conditions.

a = 5
b = 10
my_dict = {'max': a if a > b else b} # my_dict will be {'max': 10}

What is a ternary?

A ternary is a concise way to perform a conditional assignment in a single line. In the context of programming, it typically refers to a ternary operator, which evaluates a condition and returns one of two values.

How to read ternary operator?

The ternary operator syntax in Python can be read as: “if the condition is true, then return value_if_true, otherwise return value_if_false.”

# Example
result = "Positive" if num > 0 else "Negative"
# Read as: "If num is greater than 0, then result is 'Positive', otherwise result is 'Negative'."

When to use ternary operator?

Use the ternary operator for simple, concise conditional assignments when you want to make your code more readable and reduce the number of lines. It is particularly useful for short, straightforward conditions.

# Instead of this:
if a > b:
max_value = a
else:
max_value = b

# Use this:
max_value = a if a > b else b


Previous Article
Next Article

Similar Reads

Benefits of Double Division Operator over Single Division Operator in Python
The Double Division operator in Python returns the floor value for both integer and floating-point arguments after division. C/C++ Code # A Python program to demonstrate use of # &amp;quot;//&amp;quot; for both integers and floating points print(5//2) print(-5//2) print(5.0//2) Output: 2 -3 2.0 The time complexity of the program is O(1) as it conta
2 min read
Ternary Search Visualization using Pygame in Python
An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with
5 min read
Ternary contours Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Ternary contours in Plotly In plotly, ternary
3 min read
How to create a Ternary Overlay using Plotly?
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library Creating Ternary Scatter Plot A ternary scatter
2 min read
Ternary Plots in Plotly
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Ternary Plots in Plotly A ternary plot is also
2 min read
Difference between == and is operator in Python
When comparing objects in Python, the identity operator is frequently used in contexts where the equality operator == should be. In reality, it is almost never a good idea to use it when comparing data. What is == Operator?To compare objects based on their values, Python's equality operators (==) are employed. It calls the left object's __eq__() cl
3 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows d
7 min read
Python | Operator.countOf
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the number of occurrences Returns: Count of number of occ
2 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
Check if a value exists in a DataFrame using in &amp; not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg