Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Comprehension with if: Filtering and Conditional Logic

Learn how if in a Python comprehension filters items and how if-else transforms every item, along with syntax, performance, and readability guidance.

~2 min readPython
#list comprehensions#conditional filtering#python syntax#generator expressions
A visual metaphor of a Python list comprehension with an if condition filtering elements from a list, showing accepted and rejected items.

A Python comprehension with if lets you filter and transform iterables in a single expression. The placement of the if keyword determines whether you are filtering elements or choosing between two expressions for each element. Understanding this distinction is the first step to using comprehensions effectively.

Basic Syntax: Filtering with if

The most common form is [expression for item in iterable if condition]. Python evaluates the condition for each item and includes the result of expression only when the condition is true.

python
numbers = range(10) even = [n for n in numbers if n % 2 == 0] print(even) # [0, 2, 4, 6, 8]

Here, n % 2 == 0 is the filter. Items that fail the test are skipped entirely; the expression n is not evaluated for them. This is useful for extracting a subset of data without writing a loop.

Using if-else for Conditional Transformations

If you need to choose between two values for every item, place the conditional expression before the for:

python
numbers = range(5) signed = [n if n % 2 == 0 else -n for n in numbers] print(signed) # [0, -1, 2, -3, 4]

The if-else is a conditional expression, not a filter. Every item is processed, and the expression selects which value to produce. This is equivalent to a map with a lambda, but more readable.

Combining Multiple Conditions

You can chain multiple if clauses, which act as an AND operation:

python
divisible_by_6 = [n for n in range(100) if n % 2 == 0 if n % 3 == 0]

This is equivalent to [n for n in range(100) if n % 2 == 0 and n % 3 == 0]. Both forms are valid; multiple if clauses can be clearer when you want to separate distinct conditions.

Nested Comprehensions with if

When you have nested loops, each loop can have its own if:

python
pairs = [(x, y) for x in range(5) if x > 0 for y in range(5) if y > 0]

Here, the first if filters x before the inner loop runs, and the second if filters y for each x. The order matters: the if applies to the loop immediately preceding it.

Performance and Memory Considerations

List comprehensions build a full list in memory. If you only need to iterate once, a generator expression (expr for item in iterable if condition) avoids that allocation. For large data, this can reduce memory usage significantly. Comprehensions are also generally faster than manual for loops with append, but the difference is often small. If performance is critical, measure with your actual data.

Readability and Maintainability

Complex conditions can make comprehensions hard to read. If you find yourself nesting multiple loops and if clauses, consider a regular loop or a generator function. For example, a helper function can encapsulate a complicated condition, keeping the comprehension readable:

python
def is_valid(item): return item > 0 and item % 2 == 0 valid = [item for item in data if is_valid(item)]

This separates the filtering logic from the comprehension and makes the intent clearer.

Common Pitfalls and Edge Cases

  • Placing if-else after the for instead of before: [n if n%2==0 else -n for n in range(5)] is valid, but [n for n in range(5) if n%2==0 else -n] is a syntax error. The else must be part of the conditional expression, not a separate clause.
  • The if clause filters before the expression is evaluated. If the expression has side effects, they won't occur for filtered-out items.
  • In nested comprehensions, the if applies to the loop immediately before it, not to the entire comprehension. Misplacing it can change the result.
  • For dictionary and set comprehensions, the same rules apply.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.