Sub topic 3
Filtering items with an if clause
This chapter assumes you can write a basic list comprehension ([expr for item in iterable]) and that you know Python's comparison operators, and/or/not, and truthiness. By the end you will be able to add a trailing if to any comprehension. You will also be able to predict which items it keeps and know when the filter belongs in the comprehension and when it doesn't.
The shape of a filter
A trailing if clause keeps only the items for which its condition is true. Here is the loop version and the comprehension version side by side:
numbers = range(10)
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens) # [0, 2, 4, 6, 8]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]The comprehension reads in the same order as the loop. The output expression moves to the front, and the for and if clauses keep the order they have in the loop.
[ output_expression for item in iterable if condition ]The comprehension never changes the source iterable. It builds a new list, and the original stays as it was.
Order of evaluation
For each item, Python runs the steps below in order:
- Take the next item from the iterable and bind it to the loop variable.
- Evaluate the condition.
- If the condition is true, evaluate the output expression and add the result.
- If the condition is false, skip the item. The output expression is never evaluated for it.
Step 4 means a filter can protect the output expression from items that would make it fail:
values = [0, 2, 4, 0, 5]
inverses = [1 / v for v in values if v != 0]
print(inverses) # [0.5, 0.25, 0.2]Without the filter, the first 0 would raise ZeroDivisionError. The condition runs first, so the division never happens for zeros.
You can watch the order with a function that prints. This is for demonstration only:
def check(n):
print("checking", n)
return n > 1
result = [n * 10 for n in range(4) if check(n)]
print(result)
# checking 0
# checking 1
# checking 2
# checking 3
# [20, 30]The condition runs once per item, in iteration order, and the results come out in that same order. A filter never reorders items.
What counts as a condition
The condition can be any expression. Python tests its truthiness, the same as in an ordinary if statement. That allows several styles.
Comparisons and method calls are the most common:
files = ["a.py", "notes.txt", "b.py", "README.md"]
py_files = [f for f in files if f.endswith(".py")]
print(py_files) # ['a.py', 'b.py']Function calls work too, so you can name a rule that is too long to write inline:
def is_prime(n):
if n < 2:
return False
return all(n % d != 0 for d in range(2, int(n ** 0.5) + 1))
primes = [n for n in range(30) if is_prime(n)]
print(primes) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Bare truthiness keeps items that are truthy:
raw = ["ada", "", "grace", " ", "linus"]
print([s for s in raw if s]) # ['ada', 'grace', ' ', 'linus']
print([s for s in raw if s.strip()]) # ['ada', 'grace', 'linus']The string " " is not empty, so it is truthy and survives the first filter. Use s.strip() when whitespace-only strings should also go.
Falsy is not the same as missing
Bare truthiness also drops 0, 0.0, empty containers, and False. If you only mean to remove None, say so:
readings = [0, 3, None, 7, 0.0, None]
present = [r for r in readings if r is not None]
print(present) # [0, 3, 7, 0.0]
truthy = [r for r in readings if r]
print(truthy) # [3, 7]This is a common data-cleaning bug. Zero readings are real data, and if r silently discards them. Use is not None when the question is "is there a value?" and bare truthiness when the question is "is this value non-empty or nonzero?".
Combining conditions
Combine tests in a single condition with and, or, and not:
nums = range(30)
result = [n for n in nums if n % 2 == 0 and n % 3 == 0]
print(result) # [0, 6, 12, 18, 24]A comprehension also allows several if clauses in a row. They behave like and, and each one only runs if the previous one was true:
result = [n for n in nums if n % 2 == 0 if n % 3 == 0]
print(result) # [0, 6, 12, 18, 24]Both forms give the same result. Most people prefer a single if with and, since it looks like an ordinary condition. Stacked if clauses are useful when each test is long and you want one per line:
users = [
{"name": "ada", "active": True, "age": 36},
{"name": "bob", "active": False, "age": 41},
{"name": "cy", "active": True, "age": 17},
]
adults = [
u["name"]
for u in users
if u["active"]
if u["age"] >= 18
]
print(adults) # ['ada']Because and and or short-circuit, you can order tests so the cheap or protective one comes first:
data = [None, "alpha", "", "beta"]
long_names = [s for s in data if s and len(s) > 4]
print(long_names) # ['alpha']If s is None or empty, the test stops before len(s) runs. len(None) would raise a TypeError.
Filters in dict and set comprehensions
The trailing if works the same way in the other comprehension forms. Later chapters cover those forms in full, so here is only how the filter applies.
prices = {"apple": 1.2, "melon": 3.5, "kiwi": 0.8, "mango": 2.5}
cheap = {name: p for name, p in prices.items() if p < 2}
print(cheap) # {'apple': 1.2, 'kiwi': 0.8}
words = ["apple", "avocado", "banana", "blueberry", "apricot"]
a_lengths = {len(w) for w in words if w.startswith("a")}
print(a_lengths) # {5, 7}In each case the condition decides whether an item produces an entry at all. Filtering happens before any key or value is computed, so a dropped item can never overwrite an earlier entry.
Filter versus choosing a value
A trailing if is easy to confuse with an if/else inside the output expression. They look alike but do different jobs:
| Form | Where it goes | Effect on the item count |
|---|---|---|
| `[x for x in data if cond]` | After the `for` clause | Can be fewer items than the input |
| `[a if cond else b for x in data]` | Before the `for` keyword | Always one output per input item |
A trailing filter cannot have an else. This is a syntax error:
[n for n in range(5) if n % 2 == 0 else 0] # SyntaxErrorIf you want every item to produce a value, move the if/else to the front. The next chapter covers that form. If you want to drop items, keep a bare trailing if. Decide first whether items should disappear or be replaced.
Why not remove items in a loop?
A frequent first attempt at filtering is to delete unwanted items from the list while iterating over it. It fails quietly:
items = [1, 2, 2, 3, 2, 4]
for x in items:
if x == 2:
items.remove(x)
print(items) # [1, 3, 2, 4]Each remove shifts later items one position left. The loop's internal index then skips the item that moved into the removed slot, and a 2 survives. The comprehension avoids the problem because it reads the old list and builds a new one:
items = [1, 2, 2, 3, 2, 4]
items = [x for x in items if x != 2]
print(items) # [1, 3, 4]This rebinds the name items to a new list. If other variables refer to the original list and must see the change, assign into a slice instead with items[:] = [x for x in items if x != 2].
Comparison with filter()
The built-in filter() does the same job as a trailing if, but it returns a lazy iterator rather than a list:
nums = range(10)
print(list(filter(lambda n: n % 2 == 0, nums))) # [0, 2, 4, 6, 8]
print([n for n in nums if n % 2 == 0]) # [0, 2, 4, 6, 8]When the filter needs a lambda, the comprehension is usually clearer. filter(None, iterable) is a compact way to keep truthy items, and it has the same pitfall with 0 as bare truthiness. If you need a lazy result, use a generator expression with the same if, which a later chapter covers.
Common errors
- Using
elsein a trailing filter. This raises aSyntaxError. Use a leading conditional expression to replace values or a bareifto drop them. - Filtering with bare truthiness when zero is valid.
if xremoves0,0.0,"", and[]. Useif x is not Noneor an explicit comparison when those values are real data. - Writing a condition with side effects. A condition that appends to a list or writes to a file makes the comprehension hard to reason about. Keep conditions free of side effects.
- Calling an expensive function in both the condition and the output.
[f(x) for x in data if f(x) > 3]callsftwice per kept item. A later chapter shows how to compute it once with an assignment expression. - Expecting a filter to reorder or deduplicate. It only drops items. Order and duplicates in the kept items stay as they were in the source.
Summary
- A trailing
ifdrops items whose condition is false, and the output expression runs only for the items that remain. - The condition runs once per item, in order, and the kept items keep their original order.
- Multiple
ifclauses act likeand. Using oneifwithandis usually easier to read. - Bare truthiness drops every falsy value, so use
is not Nonewhen you only want to remove missing values. - The filter applies the same way to list, dict, and set comprehensions.
- A trailing
ifnever takes anelse. Replacing values is a separate construct that goes before thefor.
Exercise
Given readings = [4, 0, None, 9, 0, 2], write a list comprehension that keeps every real reading, including the zeros, and drops only None. What does it return, and what would [r for r in readings if r] return instead?
Show answer
[r for r in readings if r is not None] returns [4, 0, 9, 0, 2]. The version with bare if r returns [4, 9, 2], because 0 is falsy and gets dropped along with None.
Exercise
Write a dict comprehension over scores = {"ana": 82, "ben": 58, "cho": 91, "dev": 64} that keeps only passing scores (60 or higher) and whose values are the score minus 60. What does it return?
Show answer
{name: s - 60 for name, s in scores.items() if s >= 60} returns {'ana': 22, 'cho': 31, 'dev': 4}. The filter drops "ben" before the value s - 60 is computed.
Exercise
Why does [n for n in range(5) if n % 2 == 0 else 0] fail, and how would you rewrite it so that odd numbers become 0 instead of being dropped?
Show answer
A trailing if in a comprehension is a filter and cannot take an else, so Python raises a SyntaxError. To replace odd numbers with 0, put the conditional expression before the for: [n if n % 2 == 0 else 0 for n in range(5)], which returns [0, 0, 2, 0, 4].