Ternary operator in Python

Authors

Ternary operators in Python, are commonly referred to as conditional expressions, evaluate something dependent on whether a condition is true or false.

It allows for single-line condition testing as opposed to nested if-else.

Can imporove code readability.

Syntax

a if condition else b

The condition will be evaluated first, then either a or b is evaluated and returned based on the Boolean value of condition.

If condition evaluates to True, then a is returned, else b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

Ternary Example Python

# Conditional operator example
a, b = 1, 2
 
# Find smallest value
# Copy value of a in result if a < b else copy b
result = a if a < b else b
 
print(result)

Output

1

Ternary operator as nested if-else:


# Python program to demonstrate Ternary operator as nested if-else
a, b = 1, 2

if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")
else:
    print("a and b are equal")

Output

 b is greater than a

Example Methods using Tuples, Dictionay, and Lambda

Ternary with Tuple


# Python program to demonstrate Ternary with Tuple
a, b = 1, 2

# Use tuple for selecting an item
# (if_condition_false,if_condition_true)[condition]
# if [a<b] is true it return 1, so element with index 1 will print
# else if [a<b] is false it return 0, so element with index 0 will print
print( (b, a) [a < b] )

Output

1

Ternary with Dictionary

# Python program to demonstrate Ternary with Dictionary
a, b = 1, 2
 
# Use Dictionary for selecting an item
# if [a < b] is true then value of True key will print
# else if [a<b] is false then value of False key will print
print({True: a, False: b} [a < b])
 

Output

1

Ternary with lambda

Because we can be certain that only one expression will be evaluated in lambda, as opposed to Tuple and Dictionary, it is more efficient than the other two techniques.

# Python program to demonstrate ternary operator
a, b = 1, 2
 
print((lambda: b, lambda: a)[a < b]())

Output

1
TrackingJoy