Filtering in a comprehension (if …)
An `if` at the end of a comprehension lets through only the items that meet the condition.
Used in 95 lessons of the course, from 00.01.
A comprehension walks over a collection and builds another one. If you add if condition at the end, each item is checked first: if the condition is true, it goes in; if not, it is dropped.
You read it left to right: "give me x for each x in items if condition".
[n for n in [1, 2, 3, 4] if n > 2]
The if filters, it doesn't change the values: what comes out is what was there, just fewer. This saves you from creating an empty list and calling append inside a for with an if.
In the course you see it in the line from lesson 00.01: sorted(t for t, (d, _) in GLOSSARY.items() if word in t or word in d.lower()). It walks the glossary and keeps only the terms whose name or description contains the word. The condition can combine tests with or and and.
Reach for it when: you want to keep only part of a collection, such as the texts that contain a word or the numbers above a threshold.
Examples
Common mistake
words = ["a", "bb", "ccc"] print([w for w in words if len(w) > 1 else w])
Why: A filtering `if` does not accept `else`. `else` belongs to the conditional expression, which goes before the `for`.
How to write it: If you only want to filter, drop the else. If you want to change values, write [w if len(w) > 1 else "-" for w in words].
