Skip to content

Python Conditional Expression (Ternary Operator)

How to use Python's ternary operator for concise if-else logic in a single line, with syntax examples and common use cases.

Conditional Expressions (also known as Ternary Operators) are used to write an if statement in one line.

Conditional Expressions

if-else Conditional Expression

In Python, conditional expression syntax is as follows:

value_if_true if condition else value_if_false

where:

  • The condition is evaluated first.
  • If condition is True, value_if_true is evaluated and its value is returned
  • If condition is False, value_if_false is evaluated and its value is returned

For example:

a = 1
result = 'even' if a % 2 == 0 else 'odd'
print(result) # odd

a = 2
result = 'even' if a % 2 == 0 else 'odd'
print(result) # even

The equivalent extended form is:

if a % 2 == 0:
    result = 'even'
else:
    result = 'odd'

if-elif-else by conditional expressions

value_if_true if condition1 else value_if_true2 if condition2 else value_else

For example:

a = 2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result) # positive

Conditional Expressions with Tuple Notation

An alternative but very little-used form of Conditional Expressions involves tuples.

(if_test_is_false, if_test_is_true)[condition]

For example:

num = 10
result = ("Even", "Odd")[num % 2]
print("The number is ", result) # The number is Even

Common cases

Conditional Expressions in List Comprehensions

Using conditional expressions in list comprehension, you can apply operations to list elements based on the condition.

my_list = ['even' if i % 2 == 0 else 'odd' for i in range(10)]
print(my_list)
l = [i * 2 if i % 2 == 0 else i for i in range(10)]
print(l)
Navigation