Python ternary Operator Examples

Python doesn’t have a ternary operator. But, it supports writing an if-else statement in such a way that it works as a Python ternary operator.


Why Python doesn’t have a special ternary operator?

Many programming languages have ternary operators. But, their main purpose is to reduce the code size by removing simple if-else blocks. Python improved the if-else statements itself to reduce the code size rather than adding an additional operator.


Python ternary operator implementation

The syntax of mimicking ternary operator in Python is:

[when_true] if [condition] else [when_false]

If the condition is evaluated to True, the when_true value is returned, otherwise when_false is returned.


Python ternary operator Example

Let’s say we have a simple code to check if an integer is odd or even. We are asking the user to enter the number and printing whether it’s odd or even. We will implement it using the if-else block.

x = int(input("Please enter an integer:\n"))

if x % 2 == 0:
    int_type = 'even'
else:
    int_type = 'odd'

print(f'You entered {x} which is an {int_type} integer.')

The whole code snippet has 6 lines, out of which 4 are if-else block. This is a perfect place to use the improved if-else ternary operator support.

x = int(input("Please enter an integer:\n"))

int_type = 'even' if x % 2 == 0 else 'odd'

print(f'You entered {x} which is an {int_type} integer.')
Python Ternary Operator
Python Ternary Operator

Ternary Operator with Tuple

Python tuple also supports the ternary operator. Its syntax is:

(when_false, when_true)[condition]

If the condition is True, the first value is returned. Otherwise, the second value is returned.

Let’s convert the above example to use the ternary operator with a tuple.

x = int(input("Please enter an integer:\n"))

int_type = ('even', 'odd')[x % 2]

print(f'You entered {x} which is an {int_type} integer.')

Which is Better? if-else or tuple?

When we use the if-else based ternary operator, the condition is evaluated first.

In the tuple based implementation, the tuple elements are evaluated first and then the condition.

So, if there is some processing involved in generating both the possible values, the if-else is more efficient.

Let’s understand this with a simple code snippet.

def foo(s):
    print(f'foo called with parameter {s}')
    return s


flag = True

if flag:
    result = foo('if')
else:
    result = foo('else')

result = foo('ternary-if') if flag else foo('ternary-else')

result = (foo('tuple-true'), foo('tuple-false'))[flag]

print('Done')

Output:

foo called with parameter if
foo called with parameter ternary-if
foo called with parameter tuple-true
foo called with parameter tuple-false
Done

It’s clear from the output that the if-else based ternary operator implementation is better to use.


References: