Python Conditions in Comprehensions
What you will learn
- The filter:
ifat the end, which drops items - The choice:
a if cond else binside the expression, which changes items - The difference between the two, and how to combine them
- Several conditions with
and,orand repeatedif - Cleaning messy data and filtering records
- The syntax mistakes to avoid
1. Two kinds of condition
Lesson 12.1 built lists from every item. A condition lets you choose. There are two different places to put one, and they do different jobs:
| Position | Form | Job |
|---|---|---|
| at the end | [x for x in items if cond] |
a filter: keeps only the items where cond is true |
| in the expression | [a if cond else b for x in items] |
a choice: every item stays, but its value depends on cond |
nums = [1, 2, 3, 4, 5, 6, 7, 8]
print([n for n in nums if n % 2 == 0])
print(["even" if n % 2 == 0 else "odd" for n in nums[:4]])
[2, 4, 6, 8]
['odd', 'even', 'odd', 'even']
- The first list has 4 items: the odd numbers were dropped.
- The second list has 4 items, one for each number: none were dropped; each was turned into a word.
Quick check: which one makes a list shorter, the `if` at the end or the `if ... else` in the expression?
The if at the end (the filter). The if ... else in the expression always gives one result for every input.
2. The filter
Put if condition after the for part. The expression runs only for the items that pass:
print([n * n for n in nums if n % 2 == 1])
print([w.upper() for w in ["apple", "fig", "kiwi", "banana"] if len(w) > 3])
print([c for c in "Hello World" if c.lower() in "aeiou"])
[1, 9, 25, 49]
['APPLE', 'KIWI', 'BANANA']
['e', 'o', 'o']
It is the loop-and-if pattern from lesson 6.5, in one line:
result = []
for n in nums:
if n % 2 == 1:
result.append(n * n)
Several conditions
Combine tests with and and or (lesson 5.3), or repeat if, which means and:
print([n for n in nums if n > 3 and n < 7])
print([n for n in nums if n < 3 or n > 6])
print([n for n in nums if n % 2 == 0 if n > 4])
[4, 5, 6]
[1, 2, 7, 8]
[6, 8]
Chained comparisons work too: [n for n in nums if 3 < n < 7].
Truthiness
A filter that is just the item keeps the items that are true (lesson 5.3):
words = ["apple", "", "kiwi", "fig", "banana", " "]
print([w for w in words if w])
print([w for w in words if w.strip()])
print([x for x in [3, None, 5, None] if x is not None])
['apple', 'kiwi', 'fig', 'banana', ' ']
['apple', 'kiwi', 'fig', 'banana']
[3, 5]
if w dropped the empty text but kept the single space. if w.strip() dropped both. Use is not None when 0 or "" are valid values that must stay.
3. The choice: if ... else in the expression
When every item must produce a result, but the result depends on a condition, use the conditional expression (lesson 5.4) as the first part:
print([n if n % 2 == 0 else -n for n in nums[:4]])
print([n if n > 2 else 0 for n in nums[:4]])
print(["big" if n > 6 else "mid" if n > 3 else "small" for n in nums])
[-1, 2, -3, 4]
[0, 0, 3, 4]
['small', 'small', 'small', 'mid', 'mid', 'mid', 'big', 'big']
Here the else is required, because there must always be a value. The third line chains two choices (lesson 5.4); more than that is hard to read.
Both together
You can filter and choose in the same comprehension. The filter goes at the end, the choice in the front:
print([n * 10 if n % 2 == 0 else n for n in nums if n > 2])
[3, 40, 5, 60, 7, 80]
Read it in two steps: first, keep the numbers over 2 (the filter); second, multiply by 10 the even ones, and leave the odd ones (the choice).
4. The syntax mistakes
The two positions are not interchangeable:
| Mistake | Error |
|---|---|
else after a filter: [n for n in nums if n % 2 == 0 else 0] |
SyntaxError: invalid syntax |
a choice without else: [n if n > 1 for n in nums] |
SyntaxError: expected 'else' after 'if' expression |
The rules to remember:
- An
ifat the end has noelse. - An
ifat the front is a conditional expression, and it must have anelse.
If you want to keep n when even and use 0 otherwise, the condition goes in the front: [n if n % 2 == 0 else 0 for n in nums].
5. Cleaning messy data
Conditions make comprehensions good at cleaning lists:
vals = ["1", "x", "22", "", "3.5", "-4"]
print([int(v) for v in vals if v.isdigit()])
print([v for v in vals if not v.isdigit()])
[1, 22]
['x', '', '3.5', '-4']
isdigit (lesson 4.3) accepts only plain whole numbers, so "3.5" and "-4" were rejected. A more flexible test is a small helper function that tries the conversion (lesson 14.1 explains try and except):
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
print([float(v) for v in vals if is_number(v)])
[1.0, 22.0, 3.5, -4.0]
Calling a named function in the condition keeps the comprehension short and readable.
6. Filtering records
Conditions work well on lists of dictionaries or tuples:
people = [
{"name": "Rina", "age": 25},
{"name": "Sam", "age": 17},
{"name": "Lee", "age": 31},
]
print([p["name"] for p in people if p["age"] >= 18])
print([p["name"] if p["age"] >= 18 else p["name"].lower() for p in people])
print([(p["name"], p["age"]) for p in people if 20 < p["age"] < 30])
['Rina', 'Lee']
['Rina', 'sam', 'Lee']
[('Rina', 25)]
And with positions, using enumerate (lesson 6.6):
print([i for i, n in enumerate(nums) if n % 3 == 0])
print([n for i, n in enumerate(nums) if i % 2 == 0])
[2, 5]
[1, 3, 5, 7]
The first gives the positions of the multiples of 3, and the second keeps every other item.
7. Two for clauses and a filter
With nested for clauses, the filter can use both variables:
print([(x, y) for x in range(4) for y in range(4) if x < y])
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
These are all the pairs with x smaller than y. For a grid, apply the filter inside each row or across all of them:
matrix = [[1, -2, 3], [-4, 5, -6]]
print([[x for x in row if x > 0] for row in matrix])
print([x for row in matrix for x in row if x < 0])
print([[abs(x) if x < 0 else x for x in row] for row in matrix])
[[1, 3], [5]]
[-2, -4, -6]
[[1, 2, 3], [4, 5, 6]]
The first keeps the row structure and filters inside each row. The second flattens and filters. The third changes values and keeps everything.
8. The walrus: work out once, use twice
If the condition and the result both need the same calculation, the walrus operator := (lesson 5.6) stores it, so it is worked out once:
print([y for x in nums if (y := x * x) > 20])
print([(x, x * x) for x in range(6) if x * x > 5])
[25, 36, 49, 64]
[(3, 9), (4, 16), (5, 25)]
In the first line, y is the square, tested against 20 and then returned. In the second line, the square is worked out twice (once for the test, once for the result): fine for a cheap calculation, but use := when it is expensive.
9. Readable conditions
- Keep the condition short. If it needs several parts, name it as a function:
if is_valid(w). - One filter and one choice is the practical limit. More than that, write a loop.
- Do not hide side effects in the condition (such as adding to a set). It works, but nobody can read it.
- The
ifshould be easy to say aloud: "n squared, for each n in nums, if n is odd".
Worked example: tidy up survey answers
A survey form gave messy ages as text. Keep the valid ones, and label each person as adult or minor.
raw = ["25", " 17", "abc", "", "42 ", "-3", "200", "31"]
cleaned = [r.strip() for r in raw]
ages = [int(a) for a in cleaned if a.isdigit() and 0 < int(a) < 120]
labels = ["adult" if a >= 18 else "minor" for a in ages]
adults = [a for a in ages if a >= 18]
print(cleaned)
print(ages)
print(labels)
print(adults, round(sum(adults) / len(adults), 1))
['25', '17', 'abc', '', '42', '-3', '200', '31']
[25, 17, 42, 31]
['adult', 'minor', 'adult', 'adult']
[25, 42, 31] 32.7
| Step | Kind | What it does |
|---|---|---|
cleaned |
transform | removes stray spaces from every answer |
ages |
filter | keeps plain digits within a sensible range (abc, the empty answer, -3 and 200 are dropped) |
labels |
choice | gives one label for every age |
adults |
filter | keeps the adults only |
In a.isdigit() and 0 < int(a) < 120, the and stops early, so int(a) is only tried when the text is all digits (lesson 5.6). The ages are made up.
Common mistakes
- Putting
elseafter a filter, or leaving it out of a choice. - Mixing up the two positions: filter at the end, choice in the front.
- Using
if xto dropNonewhen0or""are valid. Useis not None. - Long, complex conditions inside a comprehension. Name them with a function.
- Expecting a choice to shorten the list. Only a filter does.
- Doing the same expensive calculation twice. Use
:=or a loop.
Key takeaways
ifat the end is a filter: it drops items and has noelse.a if cond else bat the front is a choice: every item stays, andelseis required.- Use both together: the choice in the front, the filter at the end.
- Combine tests with
and,or, chained comparisons or repeatedif; name complex tests with a function. - Use
is not Noneto dropNonesafely, and:=to avoid repeating a calculation.
Practice
1. Keep only the words of ["a", "tree", "sky", "house"] that have more than 3 letters.
Show answer
[w for w in ["a", "tree", "sky", "house"] if len(w) > 3] gives ['tree', 'house'].
2. Turn [3, -1, 4, -5] into [3, 0, 4, 0]: negatives become 0.
Show answer
[n if n > 0 else 0 for n in [3, -1, 4, -5]]. This is a choice, so the condition is in the front.
3. Why does [n for n in nums if n > 2 else 0] fail?
Show answer
A filter at the end cannot have an else. To use else, the condition must go in the front: [n if n > 2 else 0 for n in nums].
4. Get the names of the people older than 30 from a list of dictionaries with "name" and "age".
Show answer
[p["name"] for p in people if p["age"] > 30].
5. Make ["pos", "neg", "pos"] from [5, -2, 7].
Show answer
["pos" if n > 0 else "neg" for n in [5, -2, 7]].
6. Why is if x is not None safer than if x for removing missing values from [0, None, 5]?
Show answer
if x would also drop the valid value 0. is not None removes only the None.