Here's a Python comprehension that looks correct but throws a SyntaxError:
# Goal: Replace negatives with 0
result = [x for x in numbers if x >= 0 else 0]
# SyntaxError: invalid syntax
The fix isn't obvious unless you understand that Python has two completely different ways to use if in a comprehension—and they do different things.
The Two Patterns
Pattern 1: Filtering (if after for)
[x for x in items if condition]
This excludes items that fail the condition:
>>> [x for x in [1, 2, 3, 4, 5] if x > 3]
[4, 5] # Only 2 items—some were excluded
No else allowed. The if here acts as a gatekeeper.
Pattern 2: Conditional Expression (if-else before for)
[a if condition else b for x in items]
This transforms every item based on a condition:
>>> [x if x > 3 else 0 for x in [1, 2, 3, 4, 5]]
[0, 0, 0, 4, 5] # Still 5 items—none excluded
Requires else. Every item produces output.
The Critical Difference
| Type | Syntax | Output Length |
|---|---|---|
| Filter |
if after for
|
Fewer items |
| Transform |
if-else before for
|
Same items |
The Fix
Our broken code:
# WRONG
[x for x in numbers if x >= 0 else 0]
Python sees if after for and expects a filter—no else allowed.
The fix—move if-else to the expression position:
# CORRECT
[x if x >= 0 else 0 for x in numbers]
Combining Both
You can use filtering AND conditional expressions together:
>>> ["even" if x % 2 == 0 else "odd" for x in range(1, 6) if x > 2]
['odd', 'even', 'odd']
Read as: "For each x from 1-5, if x > 2 (filter), output 'even' if x is even else 'odd' (transform)."
The Mental Model
Think of it this way:
- Filter = bouncer at the door (some don't get in)
- Transform = costume party (everyone gets in, but maybe in different outfits)
Once this clicks, you'll never confuse them again.
This is adapted from my upcoming book, Zero to AI Engineer: Python Foundations.
I share excerpts like this on Substack → https://substack.com/@samuelochaba
Top comments (0)