Python › Comprehensions & Generators

How do you write a comprehension with MULTIPLE 'if' conditions, and how does that differ from combining them with 'and'?

Advanced

Answer

Multiple consecutive 'if' clauses in a comprehension are implicitly combined with logical AND — functionally identical to combining the same conditions with an explicit 'and' in a single 'if' clause, so it's purely a stylistic choice which form to use.
result = [n for n in range(20) if n % 2 == 0 if n % 3 == 0]
print(result)  # [0, 6, 12, 18]

# Equivalent using a single 'if' with 'and':
result2 = [n for n in range(20) if n % 2 == 0 and n % 3 == 0]
Real-world example Filtering a dataset by multiple independent criteria in a single, readable comprehension expression.

Common follow-ups: Is there ever a meaningful PERFORMANCE difference between multiple 'if' clauses versus one combined 'and' condition?