Sub topic 4
Choosing values with if/else in the output expression
This chapter assumes you can write a basic list comprehension, know how a trailing if filter works, and are comfortable with comparison operators and Python's one-line conditional expression, a if condition else b. The previous chapters covered filtering. Here you will learn the other place an if can appear in a comprehension, and why the two positions behave differently.
Two positions, two jobs
An if can appear in two places in a comprehension, and the position decides what it does:
- After the
forclause, it is a filter. It decides whether an item is kept. Dropped items produce no output. - Before the
forkeyword, as part of anif/elsepair, it is a conditional expression. It decides which value to produce for an item. Every item produces exactly one output.
The second form is the subject of this chapter. Its general shape is:
[value_if_true if condition else value_if_false for item in iterable]The part before for is the output expression. A conditional expression is a single expression, so it can sit there like any other.
From loop to conditional output
Suppose you want to replace every negative number with 0 and keep the rest. As a loop, this is a branch inside the loop body that appends in both cases:
numbers = [3, -1, 0, 7, -5]
clamped = []
for n in numbers:
if n > 0:
clamped.append(n)
else:
clamped.append(0)
clamped = [n if n > 0 else 0 for n in numbers]
print(clamped) # [3, 0, 0, 7, 0]Both versions produce a list the same length as the input. Compare that with a filter, which gives a shorter list:
numbers = [3, -1, 0, 7, -5]
positives = [n for n in numbers if n > 0]
print(positives) # [3, 7]
print(len(numbers), len(positives)) # 5 2A useful check: if the result must have one entry per input item, you want a conditional expression in the output. If some items should disappear, you want a trailing filter.
| Form | Where the `if` sits | `else` allowed? | Result length |
|---|---|---|---|
| Filter | After the `for` clause | No | Same as input or shorter |
| Conditional expression | Before the `for` keyword | Required | Same as input |
The else is mandatory
The most common error is mixing up the two forms. Both of these are a SyntaxError:
[n for n in numbers if n > 0 else 0]putselseafter theforclause, where only a filter is allowed.[n if n > 0 for n in numbers]leaves out theelse, but a conditional expression always needs both branches.
If you want to keep an item or drop it, use a trailing if and no else. If you want to keep an item but change its value, put the if/else before for.
Using both together
The two forms can appear in the same comprehension. The filter runs first and decides which items continue. The conditional expression then picks a value for each surviving item.
scores = [88, 42, 95, 60, 71]
grades = ["pass" if s >= 60 else "fail" for s in scores]
print(grades) # ['pass', 'fail', 'pass', 'pass', 'pass']
passing_levels = ["high" if s >= 90 else "ok" for s in scores if s >= 60]
print(passing_levels) # ['ok', 'high', 'ok', 'ok']In the second comprehension, the score 42 is removed by the filter, so only four labels are produced. Reading it aloud helps: "for each score that is at least 60, produce high if it is at least 90, otherwise ok."
Precedence: what exactly gets chosen
A conditional expression has very low precedence. Everything to the left of if is the "true" value, and everything to the right of else (up to the for) is the "false" value. This surprises people who expect the condition to apply to only part of the expression:
nums = [-2, 3]
print([n + 1 if n > 0 else 0 for n in nums]) # [0, 4]
print([n + (1 if n > 0 else 0) for n in nums]) # [-2, 4]In the first line, the output is (n + 1) when n > 0 and 0 otherwise. In the second line, the parentheses limit the conditional to the part being added. When an output expression mixes arithmetic with a conditional, add parentheses to show which reading you mean, even where Python would parse it correctly without them.
Only the chosen branch runs
Python evaluates only the branch that is selected. This lets you guard an operation that would otherwise fail:
values = [0, 4, 2]
inverses = [100 / v if v != 0 else None for v in values]
print(inverses) # [None, 25.0, 50.0]The division 100 / v is never evaluated for v == 0, so no ZeroDivisionError is raised. Be careful with the result, though. The list now mixes floats and None, and code that later sums or sorts it will fail on the None entries. Choose a fallback value that the rest of your program can handle, or filter instead if the bad items should not appear at all.
Chaining several conditions
You can chain conditional expressions to pick among more than two values. Each else leads into another conditional expression:
scores = [88, 42, 95, 60, 71]
letters = ["A" if s >= 90 else "B" if s >= 80 else "C" if s >= 70 else "F" for s in scores]
print(letters) # ['B', 'F', 'A', 'F', 'C']This works, and the conditions are checked from left to right. But it is already close to the limit of readability. Past two conditions, move the decision into a named function and call it from the comprehension:
def letter_grade(score):
if score >= 90:
return "A"
if score >= 80:
return "B"
if score >= 70:
return "C"
return "F"
scores = [88, 42, 95, 60, 71]
letters = [letter_grade(s) for s in scores]
print(letters) # ['B', 'F', 'A', 'F', 'C']The comprehension stays short, and the function can be tested by itself and given a docstring.
Conditional values in dict and set comprehensions
The same output-expression rule applies to the other comprehension types. In a dict comprehension, the conditional usually goes in the value position. Put parentheses around it, because the bare form after the colon is hard to read:
prices = {"apple": 1.2, "pear": 0, "plum": 2.5}
cleaned = {name: (price if price > 0 else None) for name, price in prices.items()}
print(cleaned) # {'apple': 1.2, 'pear': None, 'plum': 2.5}You can also compute the key conditionally. This is where the duplicate-key rule from the dict comprehension chapter matters. When several items produce the same key, the later item overwrites the earlier value:
sizes = {("big" if n > 5 else "small"): n for n in [1, 9, 3, 7]}
print(sizes) # {'small': 3, 'big': 7}The loop produced four pairs but only two keys exist. Each key keeps the position where it first appeared and the value from its last assignment. If you wanted every number grouped under its label, a dict comprehension is the wrong tool, and you would build lists with a loop and setdefault or collections.defaultdict.
In a set comprehension, the conditional chooses what goes into the set, and duplicates then collapse:
parity = {"even" if n % 2 == 0 else "odd" for n in range(10)}
print(sorted(parity)) # ['even', 'odd']Ten items went in, and two distinct values remain. The code prints sorted(parity) because sets have no guaranteed order, so printing the set itself could show the two strings in either order.
Common mistakes
- Mixing up filter and conditional. If your result is shorter than you expected, you probably used a filter. If it is longer than expected, you probably used a conditional where you meant a filter.
- Forgetting
else.[x if cond for x in xs]is aSyntaxError. You must supply the second value. - Placing
elsein the wrong position.elsebelongs only to a conditional expression in the output. A trailingifcannot have one. - Unclear precedence. The condition applies to the whole output expression on its left, not just the last term. Use parentheses when the output contains operators.
- Returning mixed types. A list of numbers and
Noneor strings is legal, but later arithmetic on it can fail. Decide on a consistent fallback. - Stacking too many branches. After two chained conditions, a helper function is almost always clearer.
Exercises
Exercise
What does [n if n % 2 == 0 else -n for n in range(5)] produce, and how many items are in the result compared with range(5)?
Show answer
It produces [0, -1, 2, -3, 4]. Even numbers are kept as they are, and odd numbers are negated. There are 5 items, the same as range(5), because a conditional expression in the output chooses a value for every item and never drops any.
Exercise
You have temps = [18, 25, -3, 31, 0]. Write one comprehension that gives ["warm", "freezing", ...]-style labels: "freezing" when the temperature is 0 or below, "warm" when it is 25 or above, and "mild" otherwise. What is the result, and why is a helper function worth considering here?
Show answer
["mild" if t > 0 and t < 25 else "freezing" if t <= 0 else "warm" for t in temps] works, and a shorter form is ["freezing" if t <= 0 else "warm" if t >= 25 else "mild" for t in temps]. The result is ['mild', 'warm', 'freezing', 'warm', 'freezing']. A helper function is worth considering because there are three outcomes, which already needs a chained conditional. A named function such as describe(t) can be tested alone and keeps the comprehension to [describe(t) for t in temps].
Exercise
What does {("big" if n > 5 else "small"): n for n in [2, 8, 4, 6]} return, and why does it have fewer entries than the input has items?
Show answer
It returns {'small': 4, 'big': 6}. Only two distinct keys are ever produced, and each later item overwrites the value stored for its key. For small, the value goes from 2 to 4, and for big it goes from 8 to 6.