Sub topic 4
Choosing values with if/else in the output expression
This chapter assumes you can write a basic list comprehension, use a trailing if filter, and read boolean expressions and comparison operators. It covers the second place an if can appear in a comprehension: the output expression.
Two different uses of if
An if can appear in two positions in a comprehension, and the two do different jobs.
- A trailing
ifcomes after theforclause. It is a filter. Items that fail the test are dropped. - An
if/elsebefore theforkeyword is a conditional expression. It picks a value for every item, so no item is dropped.
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']The input has five items and the output has five items. Each item gets one of two values, depending on the test.
Reading the conditional expression
The part before for is "even" if n % 2 == 0 else "odd". This is Python's conditional expression, which has the form:
value_if_true if condition else value_if_falseIt is an ordinary expression that produces one value. The comprehension evaluates it once per item. The else branch is required, because the expression must produce a value whichever way the test goes.
The same result written as a loop makes the structure clear:
labels = []
for n in range(5):
if n % 2 == 0:
labels.append("even")
else:
labels.append("odd")
print(labels) # ['even', 'odd', 'even', 'odd', 'even']In the loop, append is called on both branches. The conditional expression chooses the argument to append.
Combining both forms
You can use both in one comprehension. The trailing filter runs first and removes items. The conditional expression then chooses a value for each item that remains.
numbers = range(-3, 4)
signs = ["positive" if n > 0 else "negative" for n in numbers if n != 0]
print(signs) # ['negative', 'negative', 'negative', 'positive', 'positive', 'positive']Without the filter, 0 would be labeled "negative", which is wrong. The filter removes it before the output expression sees it.
Common errors
The most frequent mistake is putting the else in the wrong place. This line is a syntax error:
# SyntaxError: a trailing if cannot have an else
bad = [n for n in range(5) if n % 2 == 0 else 0]A trailing if is a filter, and a filter has no else. If you want a replacement value instead of dropping items, move the whole test to the front:
fixed = [n if n % 2 == 0 else 0 for n in range(5)]
print(fixed) # [0, 0, 2, 0, 4]A second mistake is using a filter when you wanted to keep every item. Compare these two lines:
numbers = [1, -2, 3, -4]
dropped = [n for n in numbers if n > 0]
clamped = [n if n > 0 else 0 for n in numbers]
print(dropped) # [1, 3]
print(clamped) # [1, 0, 3, 0]The first has two items, the second has four. Check the length of the result against what you expect.
Keep it readable
Conditional expressions can be chained, but each extra else if makes the line harder to read.
scores = [95, 82, 67, 40]
grades = ["A" if s >= 90 else "B" if s >= 80 else "C" if s >= 60 else "F" for s in scores]
print(grades) # ['A', 'B', 'C', 'F']This works, but it is hard to scan. With more than one else, consider a small helper function and call it from the comprehension, or use a plain loop.
Exercise
Given temps = [18, 25, 31, 12, 28], write one list comprehension that produces ["cool", "warm", "hot", "cool", "warm"]. Use "hot" for 30 and above, "warm" for 20 to 29, and "cool" for below 20.
Show answer
["hot" if t >= 30 else "warm" if t >= 20 else "cool" for t in temps]
Exercise
What is the length of [n for n in range(10) if n > 5], and what is the length of [n if n > 5 else 0 for n in range(10)]?
Show answer
The first is 4, because the trailing if drops items 0 to 5 and keeps 6, 7, 8, 9. The second is 10, because the conditional expression keeps every item and only changes the value.