Ternary Operator in Python

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:

Table of Content

  • Python Ternary If Else
  • Ternary Operator in Nested If else
  • Ternary Operator using Python Tuple
  • Ternary Operator using Python Dictionary
  • Ternary Operator using Python Lambda
  • Ternary Operator with Print Function
  • Limitations of Python Ternary Operator

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


Contact Us