Q&A-4Distinguish filtering from conditional transformation in comprehension syntax.
Answer
Filtering vs. conditional transformation in comprehensions
What I'd say first: a trailing if is a filter clause. It decides whether an element produces an output at all, so the result can be shorter than the input. An if/else in the output slot is a conditional expression: every input produces exactly one output, only the value varies. The distinction is cardinality, not style: the filter changes the length contract, the conditional expression preserves it. If downstream code assumes len(result) == len(xs), only one of these two forms is safe.
The two shapes
xs = [-2, -1, 0, 1, 2]
# Filter clause: 5 inputs -> 2 outputs
positives = [x for x in xs if x > 0] # [1, 2]
# Conditional expression in the output slot: 5 inputs -> 5 outputs
signs = ['neg' if x < 0 else 'nonneg' for x in xs]
# ['neg', 'neg', 'nonneg', 'nonneg', 'nonneg']
# Composed: filter first, transform the survivors
labels = ['big' if x > 1 else 'small' for x in xs if x > 0]
# ['small', 'big']Worked trace of the composed form
The comprehension is [OUT for x in xs if FILTER], and the filter runs before OUT is ever evaluated. Stepping through xs = [-2, -1, 0, 1, 2]:
x | x > 0 (filter) | OUT evaluated? | 'big' if x > 1 else 'small' | appended |
|---|---|---|---|---|
| -2 | False | no | — | — |
| -1 | False | no | — | — |
| 0 | False | no | — | — |
| 1 | True | yes | 1 > 1 False -> 'small' | 'small' |
| 2 | True | yes | 2 > 1 True -> 'big' | 'big' |
Result ['small', 'big']: five inputs, two outputs, and the conditional expression only ever saw 1 and 2. That ordering is the fact worth remembering: in [f(x) for x in xs if p(x)], p runs once per element and f runs only for survivors; in [a if p(x) else b for x in xs], p runs once per element and exactly one of a/b is evaluated (Python's conditional expression is lazy: the untaken branch is not evaluated).
Why the syntax can't be confused
A trailing if cannot take an else:
[x for x in xs if x > 0 else 0]
# SyntaxError: invalid syntaxThis is grammar, not an arbitrary restriction: a filter clause is a guard in the comprehension grammar, not an expression, so there is nowhere for else to attach. else only exists as part of the conditional expression A if cond else B, which must sit in the output slot before the first for. The compiler enforces the distinction for you. The same applies to the reverse mistake: [x if x > 0 for x in xs] is also a SyntaxError; the correct spelling is [x if x > 0 else 0 for x in xs]. You can stack filters ([x for x in xs if x > 0 if x < 10], ANDed), and a filter clause may follow each for in a nested comprehension.
Cost model
Both forms are O(n) time. The filter calls the predicate n times and the output expression k times, where k is the survivor count; the conditional expression calls the predicate n times and evaluates one branch n times. Memory differs: the list comprehension builds k elements versus n, so a filter that keeps 1% of a 10-million-element list allocates ~100k slots instead of 10M. As generator expressions both are lazy and O(1) extra memory. Illustrative, not benchmarked: on a 1M-element range, both forms land in the tens of milliseconds on a laptop, with the conditional expression slightly slower because it evaluates the predicate for every element and materialises a full-length list. dis.dis shows the difference structurally: the filter's conditional jump lands before the output expression, while the conditional expression's jump sits inside it.
Failure modes
- Predicate exceptions. In the filter form,
p(x)raising means that element is never transformed: the exception surfaces during iteration, beforefis called. In the transform form,p(x)raising kills the whole comprehension at that element. - Generator laziness.
g = (1/x for x in xs if x != 0)raises nothing until you iterate to the offending element, so aZeroDivisionErrorcan surface far from the construction site, e.g. insidesum(g)in another function. - Cardinality contracts. Downstream code assuming
len(result) == len(xs)breaks silently with a filter. If the requirement is one output per input, use the conditional expression; if only some inputs matter, use the filter.
Rule of thumb
Ask: does every input deserve an output? Yes -> conditional expression (A if p(x) else B) in the output slot. No -> trailing if p(x) filter. Both -> filter clause first, conditional expression second, and remember the filter's predicate never sees the elements it rejected. The builtins mirror this: filter() and itertools.filterfalse() are the selection side, map() is the transform side, and the walrus lets you filter on a computed value without recomputing it. [y for x in xs if (y := f(x)) > 0] (Python 3.8+).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.