Advertisement
Beginner Python, Comprehensions & Generators

How do you add a filtering condition to a list comprehension using 'if'?

Short answer

Add an 'if condition' clause after the 'for' clause; only items for which the condition is truthy are included in the resulting list, exactly like a for loop with a nested 'if' before the append.

Save Python mock interview
Advertisement
AModel answer
Add an 'if condition' clause after the 'for' clause; only items for which the condition is truthy are included in the resulting list, exactly like a for loop with a nested 'if' before the append.
evens = [n for n in range(10) if n % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]
Real-world example
Filtering a list of numbers or objects down to just the ones matching a specific condition, in a single expression.
Likely follow-ups
  • How would you write an if/else (ternary) expression INSIDE the comprehension, versus a filtering 'if'?
Related topics