Sub topic 3
Filtering items with an if clause
This chapter assumes you can write a basic list comprehension, [expression for item in iterable], and that you know comparison operators and truthiness. Here you will add a filter so the comprehension keeps only some items.
The working model
A trailing if clause goes after the for clause. For each item, Python evaluates the condition first. If the condition is true, Python evaluates the output expression and adds the result. If it is false, Python skips the item and never evaluates the output expression.
The equivalent loop makes the order clear:
even_squares = []
for n in range(10):
if n % 2 == 0:
even_squares.append(n * n)
even_squares = [n * n for n in range(10) if n % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]The if in the comprehension sits where the if sits in the loop, just after the for. The output expression moves to the front, as it did in the previous chapter.
The filter runs before the output expression
Because skipped items never reach the output expression, the filter can protect that expression from bad input:
values = ["4", "x", "10", ""]
numbers = [int(v) for v in values if v.isdigit()]
print(numbers) # [4, 10]Without the filter, int("x") would raise ValueError. The filter tests the original item, not the transformed result. Here it tests v, not int(v).
Filtering on truthiness
The condition can be any expression. Python reads it as true or false using the usual truthiness rules, so empty strings, 0, None, and empty containers are dropped:
names = ["Ada", "", "Grace", ""]
present = [name for name in names if name]
print(present) # ['Ada', 'Grace']Use this form when you really mean "keep non-empty values". If 0 is a valid value in your data, write the comparison explicitly, for example if n is not None.
Several conditions
You can combine conditions with and and or, or stack more than one if clause. Stacked clauses behave like and:
a = [n for n in range(30) if n % 2 == 0 if n % 3 == 0]
b = [n for n in range(30) if n % 2 == 0 and n % 3 == 0]
print(a) # [0, 6, 12, 18, 24]
print(a == b) # TruePrefer a single if with and. It is the form most readers expect.
Filtering is not the same as choosing a value
A trailing if removes items, so the result can be shorter than the input. It cannot change what a kept item becomes. If you want every item to appear in the result, with a different value depending on a condition, you need a conditional expression in the output position. The next chapter covers that.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `else` after a trailing `if` | `SyntaxError` | Move `if/else` into the output expression, or drop the `else` |
| Filtering on the transformed value by accident | Wrong items are kept | Test the loop variable, or use an assignment expression (covered later) |
| Using `if x` when `0` or `""` is valid data | Valid items are dropped | Compare explicitly, such as `if x is not None` |
| Calling a function with side effects in the condition | Hard to read, and runs once per item | Use a plain loop |
Same clause, other containers
The trailing if works the same way in dict and set comprehensions. Only the brackets and the output form change:
scores = {"ana": 91, "ben": 58, "cy": 74}
passed = {name: score for name, score in scores.items() if score >= 60}
print(passed) # {'ana': 91, 'cy': 74}Exercise
Given words = ["go", "python", "tea", "loop", "a"], write one list comprehension that returns the uppercase version of only the words longer than 3 letters. What does it produce?
Show answer
[w.upper() for w in words if len(w) > 3] produces ['PYTHON', 'LOOP']. The filter len(w) > 3 runs first and tests the original word. Only "python" and "loop" pass, and .upper() is applied to those two.