Sub topic 13
One-Line Conditional Expressions
This chapter covers the conditional expression, Python's inline form of if/else. It assumes you can write if, elif, and else statements, you know truthiness, and you can define simple functions. By the end you should know when a one-liner helps and when a regular statement reads better.
Statement versus expression
An if statement runs a block of code. It does not produce a value. A conditional expression is different: it evaluates to a value, so it can appear anywhere a value can, such as the right side of an assignment, an argument to a function, or a return value.
The syntax is:
value_if_true if condition else value_if_falseThe condition sits in the middle. This order surprises people coming from languages with condition ? a : b. Python puts the likely or "normal" value first and the condition second, so the line reads like English.
n = 4
label = 'even' if n % 2 == 0 else 'odd'
print(label)This prints even. It does the same job as this statement form:
n = 4
if n % 2 == 0:
label = 'even'
else:
label = 'odd'
print(label)The one-line form is shorter, and it makes plain that the only goal is to assign label.
How Python evaluates it
Python evaluates the condition first. It then evaluates only the chosen branch. The other branch is never run.
Because only one branch runs, you can use the expression to guard an operation that would fail on some inputs.
numbers = []
average = sum(numbers) / len(numbers) if numbers else 0
print(average)When numbers is empty, the condition numbers is falsy. Python skips sum(numbers) / len(numbers), so there is no ZeroDivisionError. The program prints 0.
You can see the skipping directly with a function that reports when it runs:
def loud(value):
print('evaluating', value)
return value
result = loud('A') if True else loud('B')
print(result)The output is evaluating A followed by A. The call loud('B') never happens.
Where you can use it
A conditional expression is a value, so it works in many places.
def describe(temp):
return 'hot' if temp > 30 else 'mild'
print(describe(35))
print(describe(20))
age = 17
print('Entry:', 'allowed' if age >= 18 else 'denied')
names = ['ada', '', 'grace', '']
cleaned = [name if name else 'unknown' for name in names]
print(cleaned)The output is:
hot
mild
Entry: denied
['ada', 'unknown', 'grace', 'unknown']The list comprehension case is worth noting. When the conditional expression is the item expression, it goes before the for. This is different from a filter, where if comes after the for and has no else.
nums = [1, 2, 3, 4, 5, 6]
# Transform: every item stays, value changes
labels = ['even' if n % 2 == 0 else 'odd' for n in nums]
# Filter: some items are dropped
evens = [n for n in nums if n % 2 == 0]
print(labels)
print(evens)The first list has six items. The second has three. Mixing up the two forms is a common source of SyntaxError.
Operator precedence and parentheses
A conditional expression has very low precedence. Only lambda and the assignment forms bind more loosely. This means the whole text on each side is treated as one operand, which is usually what you want, but a few cases need parentheses.
x = 5
y = 'big' if x > 3 else 'small' + '!'
print(y)This prints big. The + '!' belongs to the else branch only, so it would apply only when the condition is false. To add ! in both cases, wrap the expression:
x = 5
y = ('big' if x > 3 else 'small') + '!'
print(y)This prints big!. When you combine a conditional expression with other operators, add parentheses even where Python does not require them. They cost nothing and remove doubt.
Chaining conditional expressions
The else branch can itself be a conditional expression. This gives you an elif-like chain on one line.
score = 83
grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'F'
print(grade)This prints B. Python reads it as 'A' if score >= 90 else ('B' if score >= 80 else (...)). It works, and the evaluation order is the same as an elif chain: top to bottom, first match wins.
It is hard to read, though. Compare it with the statement version from the earlier chapter on elif. For more than two outcomes, the statement form is usually the better choice. If you do chain, break the expression across lines inside parentheses:
score = 83
grade = (
'A' if score >= 90 else
'B' if score >= 80 else
'C' if score >= 70 else
'F'
)
print(grade)A practical rule: one if/else pair in an expression is fine. Two is borderline. Three or more should become an if/elif/else statement or a match statement.
Choosing between a value and an action
A conditional expression chooses between two values. It cannot choose between two statements. This is a frequent mistake:
# SyntaxError: assignment and print are statements, not expressions
# 'adult' if age >= 18 else print('minor') <- works only by accidentTechnically, print(...) is a call and therefore an expression, so code like this can run. It is still poor style, because it uses an expression for its side effect and throws the value away.
age = 20
# Poor style: expression used only for its side effect
print('adult') if age >= 18 else print('minor')
# Better: choose the value, then act once
print('adult' if age >= 18 else 'minor')
# Or use a normal statement when the branches do different things
if age >= 18:
print('adult')
else:
print('minor')Use the expression when you are picking a value. Use a statement when each branch performs actions, such as assigning several variables, logging, or returning early.
Related idioms and their traps
The `and`/`or` trick
Before conditional expressions existed (before Python 2.5), people wrote condition and a or b. You will still see it in old code. It fails when a is falsy.
use_default = True
value = use_default and '' or 'fallback'
print(value)The intent was to return '', but the output is fallback, because '' is falsy and or moves on to the next operand. The conditional expression has no such problem:
use_default = True
value = '' if use_default else 'fallback'
print(repr(value))This prints ''. Prefer the conditional expression in new code.
Defaults with `or`
A related and legitimate idiom is value or default. It is short-circuiting and returns the first truthy operand.
name = ''
display = name or 'anonymous'
print(display)This prints anonymous. Be careful, because 0, '', [], and None are all treated the same. If 0 is a valid value, test explicitly:
count = 0
shown = count if count is not None else 10
print(shown)This prints 0. Writing count or 10 here would wrongly give 10. This connects to the earlier chapter on truthiness and is None.
Using `None` checks in the condition
Conditional expressions work well for optional values:
def greet(name=None):
return f'Hello, {name}' if name is not None else 'Hello, stranger'
print(greet('Ada'))
print(greet())Output:
Hello, Ada
Hello, strangerWhen to avoid the one-liner
Use a regular statement in these cases:
- The line is longer than about 80 to 100 characters and wraps awkwardly.
- You need more than one
ifandelsepair. - Either branch needs side effects, multiple steps, or a comment.
- The condition is itself a long
and/orcombination. Give it a name first.
# Hard to scan
fee = 0 if (member and years >= 2) or (age >= 65 and not blocked) else 25
# Clearer: name the condition
eligible = (member and years >= 2) or (age >= 65 and not blocked)
fee = 0 if eligible else 25The second form tells the reader what the condition means. That is usually worth an extra line.
Quick reference
| Goal | Form |
|---|---|
| Pick one of two values | `a if cond else b` |
| Default for a falsy value | `x or default` |
| Default only for `None` | `x if x is not None else default` |
| Transform every item in a comprehension | `[a if cond else b for item in seq]` |
| Drop some items in a comprehension | `[item for item in seq if cond]` |
| Three or more outcomes | `if`/`elif`/`else` or `match` |
Exercises
Exercise
What does this code print, and why? x = 10 result = 'big' if x > 5 else 'small' + '?' print(result)
Show answer
It prints big. The conditional expression has low precedence, so + '?' belongs to the else branch only. Since x > 5 is True, the else branch is never evaluated and no ? is added. To append ? in both cases, write ('big' if x > 5 else 'small') + '?'.
Exercise
A function receives limit, which may be None (not set), 0 (a valid limit), or a positive integer. Write a one-line conditional expression that gives limit unchanged when it is set, and 100 when it is None. Why is limit or 100 wrong here?
Show answer
Use limit if limit is not None else 100. The expression limit or 100 treats 0 as falsy, so a valid limit of 0 would be replaced by 100. The explicit is not None test replaces only the missing value.
Exercise
Rewrite this statement as a single conditional expression assigned to message, and say whether the one-liner is a good choice.
if count == 1:
message = '1 item'
else:
message = str(count) + ' items'
Show answer
message = '1 item' if count == 1 else str(count) + ' items'. It is a good choice because there is one condition, two outcomes, and each branch only produces a value. An f-string version is also reasonable: message = '1 item' if count == 1 else f'{count} items'.