Filter: the trailing if
[n for n in nums if n % 2 == 0]
This drops items. Six numbers in, three out. The if sits after the for. It takes no else. There is nowhere for a fallback to go. A filter either keeps an item or drops it.
Writing [n for n in nums if n % 2 == 0 else 0] is a syntax error. It is worth trying once so the error message becomes familiar.
The trailing if is for filtering: reducing the number of items in the output. Every item in the source iterable is tested, and only those that pass appear in the result. This is the comprehension equivalent of wrapping the loop body in an if statement and only appending when the condition is true.
When you want to keep every item but change some of them, filtering is the wrong tool. You need a conditional expression in the output slot instead. [n if n > 0 else 0 for n in nums] keeps every item but replaces negatives with zero. Notice the position: the conditional expression comes before the for, not after it. That position difference is how Python tells filtering apart from transforming.
You can combine both. [n * 2 if n > 0 else 0 for n in nums if n != 5] filters out fives, doubles positives, and replaces non-positives with zero. The trailing if runs first, deciding which items enter the comprehension at all. The conditional expression in the output slot runs second, choosing what value to produce for each surviving item.
This two-position rule is the single most confusing thing about comprehensions. The trailing if after for is a filter with no else. The if/else before for is a conditional expression that must have both branches. They look similar but serve different purposes and sit in different places.
Reading them aloud helps. "For each n in nums, if n is even, keep it" is a filter. "For each n in nums, double it if positive, otherwise zero" is a conditional expression. The position in the comprehension matches the position in the English sentence.
This page covers the filter syntax, the conditional expression syntax, combining both, and the common mistakes that come from mixing up the two positions.
Choose: the conditional expression
["even" if n % 2 == 0 else "odd" for n in nums]
This drops nothing. Six numbers in, six strings out. The if/else is part of the formula at the front. It's the if-based formula from earlier in the track, used inside a comprehension. So it must be complete, and the else is mandatory.
Together
["big" if n > 4 else "small" for n in nums if n % 2 == 0]
Read it in run order rather than left to right. Take each n, keep it only if it's even, then turn what lives into "big" or "small". The filter runs first.
That sorting isn't a detail. If the filter is dropping None values, the formula never sees them:
["pass" if r["score"] >= 50 else "fail"
for r in rows if r["score"] is not None]
Swap the two and the check raises on the first missing score.
Several filters
[n for n in nums if n % 3 == 0 if n % 5 == 0]
Chained filters mean the same as one and. The and version is often clearer. The chained form is worth recognising because you'll meet it.
In nested comprehensions
[n for row in grid for n in row if n % 2]
A trailing if attaches to the clause it follows. Here the inner loop. Placing a filter after the first for instead would filter rows rather than cells. When there are two loops and a rule, this is where a comprehension starts costing more to read than it saves. The loop version is the kinder choice.
Filtering out None before working with values
The combination above isn't a contrived example. It's the common shape when data has gaps. Guarding in the filter means the formula at the front never sees a None, which lets it do math or call methods without a defensive check:
[r["score"] * 2 for r in rows if r["score"] is not None]
Written the other way round - a if-based formula testing for None on each item - the line is longer and still makes an entry for rows that had no score, which is often not what was wanted.
Where to draw the line
A comprehension carrying a filter, a if-based formula and a nested loop is a program written on one line. It will be correct and it will cost each future reader - including you - a slow minute. The loop version is four lines that never need decoding, and no reviewer has ever objected to it.
The difference is easiest to hold on to as a length:
nums = [1, -2, 3, -4]
print([n for n in nums if n > 0])
print([n if n > 0 else 0 for n in nums])
print([n if n > 0 else 0 for n in nums if n % 2])
[1, 3]
[1, 0, 3, 0]
[1, 3]
The first is a filter: four in, two out. The second is a choice: four in, four out, with the failures replaced rather than removed. The third has both, and the reading order is the thing to fix in your head — the trailing filter runs first, keeping the odd numbers, and only then does the leading if-based run on what survived.
Written out as a loop, the order is obvious:
result = []
for n in nums:
if n % 2: # the trailing filter
result.append(n if n > 0 else 0)
The comprehension writes the append formula first and the filter last, which is the reverse of the order they execute in. That is the single fact that makes mixed comprehensions hard to read, and it's why one filter and one if-based is a sensible ceiling.
Why the else is compulsory in one place and forbidden in the other
This looks like an inconsistency and is a direct consequence of what each if is doing.
The if at the front is part of the formula that makes each item. An formula must give a value on each path — there's nowhere for "give nothing" to go, because the comprehension is going to append what it tests to. So the else is needed, just as it's in a if-based formula anywhere else.
The if at the end is a filter clause, part of the comprehension's machinery rather than of the formula. It answers one question: does this item continue to the formula, or not. There's no second branch for an else to introduce, because "not kept" is already the option.
Trying the wrong one is worth doing once so the error is familiar. [n for n in nums if n > 0 else 0] is a SyntaxError, and the message points at the else. [n if n > 0 for n in nums] is also a SyntaxError, because the formula is incomplete.
Filtering to make the expression safe
The run order isn't trivia. It's what lets the filter protect the formula:
rows = [{"score": 50}, {"score": None}, {"score": 90}]
print([r["score"] * 2 for r in rows if r["score"] is not None])
[100, 180]
The None row never reaches the times. Swap the two clauses in your head — formula first — and it would raise TypeError on the second row.
This is the standard shape for data with gaps, and it's better than the option it's often confused with. Writing [r["score"] * 2 if r["score"] isn't None else None for r in rows] makes an entry for each row, including a None in the middle of what is supposed to be a list of numbers. This Pushes the problem to what consumes the result.
Deciding between them is deciding what a missing value means: filter when the row shouldn't be in the output, choose when it should be present with a substitute. Both are legitimate. Picking one by accident isn't.
Several filters, and the nested case
Chained filters mean and:
[n for n in nums if n > 0 if n % 2 == 0]
is the same to one filter with and. The chained form at times reads better when the rules are unrelated tests. The mixed form is more familiar. Neither is wrong.
Nesting is where care is needed. A trailing if attaches to the clause it follows:
[n for row in grid for n in row if n % 2]
The filter is after the inner for. So It filters cells. Move it up, to for row in grid if len(row) > 2 for n in row, and it filters rows instead. Both are legal and they mean fully different things, with no visual signal beyond spot.
The clauses read in the same order as the equal nested loops, outermost first. That is worth stating because the guess most people make is the opposite, and the code will run either way while making the wrong answer.
The same two positions, everywhere
Nothing on this page is exact to lists. Dict comprehensions, set comprehensions and gen expressions all carry the same two if spots with the same rules, and knowing that means learning it once.
rows = [{"name": "ana", "score": 91}, {"name": "bo", "score": None}]
print({r["name"]: r["score"] for r in rows if r["score"] is not None})
print({r["name"] for r in rows if r["score"]})
print(sum(r["score"] for r in rows if r["score"] is not None))
{'ana': 91}
{'ana'}
91
The filter sits at the end in all three. A if-based formula, when used, sits at the front — in the value slot for a dict, in the item slot for a set or gen. In a dict comprehension it can appear in either the key or the value, or both. This Is legal and almost always worse than a loop.
The gen formula case is worth calling out because the filter there's doing a thing the others aren't: it decides which items are ever found at all. In a list comprehension a filtered-out item costs a test. In a gen feeding sum over a large file, the filter is what stops work from happening.
When the filter is expensive
The trailing filter runs on each item, and the leading formula runs only on survivors. That is often the fast way round, and at times it isn't.
If the test itself is costly. A lookup, a regular formula, a parse — and the formula needs the same found value, the naive comprehension does the work twice:
[parse(line) for line in lines if parse(line) is not None]
parse runs twice for each line that lives. The walrus operator finds it once and reuses it:
[value for line in lines if (value := parse(line)) is not None]
The set happens in the filter, and the name is available to the formula at the front — which reads oddly, since the formula is written first, but follows right from the filter running first.
Before Python 3.8 the idiom was a nested comprehension: [v for v in (parse(l) for l in lines) if v isn't None], finding the values in an inner gen and filtering the results. That still works and is arguably clearer, since it separates the two steps rather than hiding an set inside a rule.
The rule, in one line
All on this page reduces to a sentence worth keeping: **the if at the front chooses a value and needs an else. The if at the end chooses an item and can't have one.**
If you can only note one consequence of that, make it the length. A comprehension whose result must be the same length as the input needs the leading form. One whose result may be shorter needs the trailing form. Asking "how many items should come out" answers which if you want faster than recalling the syntax rules does.
And when both appear, note they run in the opposite order to the one they are written in. The filter decides what lives. The formula then decides what each survivor turns. each confusing mixed comprehension is that inversion catching someone out.
Questions people ask about Conditional Comprehensions
Which if runs first? The trailing filter, always — though the if-based formula is written before it.
Can I use else with the trailing if? No, it's a syntax error. There's no second branch for a filter.
Can I filter on the found value rather than the source? Not right, without finding it twice. The walrus operator does it in one pass: [y for x in data if (y := f(x)) > 0].
Does this work in dict and set comprehensions? Yes, the same way. The two spots and their rules are the same in all of them.
Are two filters slower than one and? No, they compile to the same thing.
How many clauses is too many? One for, one filter, and optionally one if-based formula. Past that, the loop is easier to read and to change.
Can the filter ref the loop variable of an outer clause? Yes. each clause can see the variables bound by the clauses to its left.
Can I put the filter before the for? No. The clause order is fixed: formula, then for, then any if. The only if that comes first is part of the formula.
Why does my comprehension raise on some items? Almost always because the formula is running on items the filter should have removed — or because the filter is testing a thing different from what the formula uses.
Is there a way to skip an item from the formula? No. An formula must give a thing. So Skipping is the filter's job. That gap is the reason for the two spots.
Do comprehensions with filters build the list lazily? No, a list comprehension builds the whole thing. Use a gen formula when the filtering should happen on demand.
Can I filter on the index? Only by supplying one: [x for i, x in enumerate(items) if i % 2 == 0].
Conditional Comprehensions: recap in one screen
- The trailing
if filters and takes no else. The leading if/else chooses and needs one. - Filter first, then the formula. The opposite of the written order.
- That sorting is what lets a filter guard the formula against
None or a division by zero. - Chained filters mean
and. In a nested comprehension a filter attaches to the clause it follows. - One
for, one filter, one if-based: past that a loop reads better and changes more safely.