In a list comprehension, where does the if go: before or after the for?
A filter if goes after the for clause and drops items. An if-else that chooses between two values is an expression, so it goes before the for. Writing else after the for is a SyntaxError.
Explain it simply
Two different jobs look alike.
Filtering is a gate at the door: "only let in students above 35". Gate rules come after the loop: for m in marks if m > 35.
Choosing is a stamp on each person: "mark PASS or FAIL for everyone". Every item gets a result, so the stamp comes in front, as "PASS" if m > 35 else "FAIL".
Example
marks = [20, 50, 35, 80]
filtered = [m for m in marks if m > 35]
print(filtered) # Output: [50, 80]
labels = ["PASS" if m > 35 else "FAIL" for m in marks]
print(labels) # Output: ['FAIL', 'PASS', 'FAIL', 'PASS']
both = ["PASS" if m > 35 else "FAIL" for m in marks if m != 35]
print(both) # Output: ['FAIL', 'PASS', 'PASS']The last line uses both: first the gate removes 35, then the stamp labels the rest.
What to say in the interview
"A trailing if filters and the result can be shorter. An if-else is a conditional expression that picks a value for every item, so it sits at the front. Putting else after the for clause is a SyntaxError. They can be combined in one comprehension."
Common mistakes
- Writing
[m for m in marks if m > 35 else 0], which does not parse.