Skip to main content

Python Ternary Operator

Satellite · Control Flow

Python Ternary Operator

Inline conditionals replace multi-line if/else blocks when you only need to choose one expression.

Syntax

Python's ternary operator is officially called a conditional expression. The condition sits in the middle:

value_if_true if condition else value_if_false
total = 120
status = "premium" if total > 100 else "standard"
print(status) # -> premium

Compare it with the equivalent if/else block:

total = 120
if total > 100:
status = "premium"
else:
status = "standard"
print(status) # -> premium

Both assign the same value. The conditional expression earns its place when the whole decision is "pick one of two values" — it keeps the assignment on one line and makes clear that status is always set. If either branch needs multiple statements, use the block form.

Evaluation order

The condition is evaluated first, and then only the chosen branch runs — the other branch is never touched. You can prove it with a function that prints when called:

def expensive():
print("expensive ran")
return "computed"

x = 5
value = "cached" if x < 10 else expensive()
print(value) # -> cached
# note: "expensive ran" never printed — the else branch was skipped

This laziness makes conditional expressions safe as guards:

denominator = 0
result = 0 if denominator == 0 else 100 / denominator
print(result) # -> 0 (100 / denominator was never evaluated)

If both branches were evaluated eagerly, that line would raise ZeroDivisionError. It doesn't.

In f-strings and comprehensions

Because it is an expression, a ternary fits anywhere an expression can go. Inside an f-string it handles pluralization neatly:

count = 1
print(f"{count} item{'s' if count != 1 else ''}") # -> 1 item

count = 3
print(f"{count} item{'s' if count != 1 else ''}") # -> 3 items

Inside a list comprehension, it transforms every item (unlike the trailing if, which filters):

scores = [82, 45, 91]
labels = ["pass" if s >= 60 else "fail" for s in scores]
print(labels) # -> ['pass', 'fail', 'pass']

When embedding a ternary inside a longer expression, wrap it in parentheses so the boundaries are obvious: price * (0.9 if member else 1.0).

Why nested ternaries hurt

Ternaries chain from left to right, and the result is technically valid Python:

score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(grade) # -> B

It works, but the reader has to mentally re-nest the chain to find which condition wins. The if/elif ladder states the same logic in the order it is checked:

score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # -> B

Rule of thumb: one condition per ternary. The moment you type a second if, switch to if/elif.

Frequently Asked Questions

Does Python have a ?: ternary operator like C or JavaScript?

Not with that symbol. Python uses the conditional expression a if condition else b, which does the same job. Writing condition ? a : b is a syntax error in Python.

age = 20
label = "adult" if age >= 18 else "minor"
print(label) # -> adult

Is the unused branch of a ternary evaluated?

No. The condition is evaluated first, and only the selected branch is executed. That is why an expression like 0 if n == 0 else total / n never raises ZeroDivisionError.

Can I write a ternary without an else?

No — the conditional expression requires both branches, because it must always produce a value. If you only want to act when the condition is true, use a normal if statement. For "value or fallback" you can use the or idiom, but remember it replaces every falsy value (0, "", []), not just None.

name = ""
display = name or "Anonymous"
print(display) # -> Anonymous

Next up in your learning path