What's the Syntax for Ternary Operator in Python?

Introduced in Python 2.5, the syntax for the ternary operator (or conditional expression) is:

# Python 2.5+
expr_1 if condition else expr_2

Where the "condition" must evaluate to either True or False, and accordingly return either expr_1 or expr_2 — i.e.:

  • expr_1 is returned if condition evaluates to True;
  • expr_2 is returned if condition evaluates to False.

This is merely a shorthand for writing if-else in the following way:

if condition:
    return expr_1
else:
    return expr_2

For example, you can use a ternary to conditionally return a string indicating even/odd numbers from a number argument, like so:

# Python 2.5+
def num_type(num):
    return 'even' if num % 2 == 0 else 'odd'

print(num_type(1)) # 'odd'
print(num_type(2)) # 'even'
# ...

You can write the same in if-else form, for example, like so:

def num_type(num):
    if num % 2 == 0:
        return 'even'
    else:
        return 'odd'

print(num_type(1)) # 'odd'
print(num_type(2)) # 'even'
# ...

You can also use ternary operator to write complex, nested if-else conditionals in a compact form, for example, like so:

# Python 2.5+
def compare(a, b):
    return 0 if a == b else 1 if a > b else -1

print(compare(1, 2)) # -1
print(compare(2, 1)) # 1
print(compare(2, 2)) # 0
# ...

This is the same as using if-else in the following way:

def compare(a, b):
    if a == b:
        return 0
    else:
        if a > b:
            return 1
        else:
            return -1

print(compare(1, 2)) # -1
print(compare(2, 1)) # 1
print(compare(2, 2)) # 0
# ...

Although nested ternary operators can be useful for writing more complex conditionals in a compact form, they can also make the code more difficult to read, especially if the expressions and conditions become complex. In such cases, it's often better to use multiple lines of code with if-else statements.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.