Skip to content
PythonComprehensions and Functional Patternsbeginner25 min read

Comprehensions with Conditions

Filter items, transform selected values, and choose between conditional expressions inside Python list comprehensions.

In this lesson, you will learn

  • ✓Explain how an if filter controls which items enter a list comprehension.
  • ✓Distinguish filtering items from transforming their values.
  • ✓Predict the result of comprehensions containing conditions.
  • ✓Use conditional expressions with if and else to choose output values.
  • ✓Trace comprehensions step by step and handle empty results and negative values.
  • ✓Write readable conditional comprehensions and recognize when a regular loop is clearer.

1. Filtering items with if

A filtered list comprehension creates a new list containing only the items that satisfy a condition. Python evaluates the condition for each item. If the condition is true, the item is included; if it is false, that item is skipped.

The general syntax is [expression for item in iterable if condition]. The iterable supplies the items, the if clause decides which items are accepted, and the expression determines what value is placed in the resulting list.

The if clause in this syntax is a filter. It does not provide an alternative value when the condition is false. The item is simply excluded from the result.

A condition is any expression that Python evaluates as true or false. Common examples include n > 0, n % 2 == 0, name.startswith('A'), and len(word) > 3.

Keep only even numbers

Keep only even numbers
python
numbers = [1, 2, 3, 4, 5, 6, 7]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
Output
[2, 4, 6]

Python visits each number in the original list. The expression n % 2 == 0 is true for 2, 4, and 6 because those numbers have a remainder of zero when divided by 2. Only the accepted numbers enter the new list. The other numbers are skipped. The original numbers list is not modified.

Note

Filtering preserves the relative order of accepted items. If no items satisfy the condition, the comprehension produces an empty list: [].

2. Understand the evaluation order

To trace a filtered comprehension, imagine Python visiting the items in the iterable one at a time. For each item, Python evaluates the filter condition. If the condition is true, Python evaluates the expression that contributes a value to the result. If the condition is false, that item contributes nothing.

For a basic comprehension such as [n * 10 for n in numbers if n % 2 == 1], the filter is checked before the multiplication is used to create a result value. You can think of it as selecting the items first and transforming the selected items.

The comprehension does not repeatedly change the original list. It builds a new list from the values produced by the expression.

Trace each item

Trace each item
python
numbers = [1, 2, 3, 4, 5]
result = [n * 10 for n in numbers if n % 2 == 1]
print(result)
Output
[10, 30, 50]

For n = 1, the condition is true, so 1 * 10 contributes 10. For n = 2, the condition is false, so nothing is added. For n = 3, the condition is true, so 3 * 10 contributes 30. For n = 4, the condition is false, so nothing is added. For n = 5, the condition is true, so 5 * 10 contributes 50. The completed list is [10, 30, 50].

Note

When tracing a comprehension, write down the current item, whether the condition passes, and the value added. This makes the result much easier to predict.

3. Filter and transform in the same comprehension

Filtering and transforming can be combined in one list comprehension. The if filter decides which input items are accepted, while the expression before for decides which values appear in the result.

These two jobs are independent. A comprehension may keep an item unchanged, as in [n for n in numbers if n > 0], or produce a different value for every accepted item, as in [n * n for n in numbers if n > 0].

The expression determines the result's values; the filter determines which iterations contribute a value. Remembering this distinction prevents a common source of confusion.

Keep positive numbers and square them

Keep positive numbers and square them
python
numbers = [-3, -1, 0, 2, 4]
squares = [n ** 2 for n in numbers if n > 0]
print(squares)
Output
[4, 16]

The filter n > 0 accepts only 2 and 4. The expression n ** 2 converts those accepted values to their squares. The negative numbers and zero do not contribute any values.

Caution

Do not confuse the filter with the expression. In [n * 2 for n in numbers if n > 0], the condition does not double the number. The expression n * 2 does that, and the condition only determines which numbers are processed.

4. Conditional expressions: choose a value with if and else

A conditional expression is different from a comprehension filter. It has the form value_if_true if condition else value_if_false. It chooses one of two values for each item.

When a conditional expression is placed before for, every item in the iterable contributes a result value, unless the expression itself raises an error. The condition chooses which value to contribute rather than deciding whether the item is included.

Compare [n for n in numbers if n > 0] with ['positive' if n > 0 else 'not positive' for n in numbers]. The first comprehension excludes values that are not positive. The second produces a label for every input number.

A conditional expression must include else. An expression such as 'positive' if n > 0 is incomplete because it does not specify what value to use when the condition is false.

Label every number

Label every number
python
numbers = [-2, 0, 5]
labels = ['positive' if n > 0 else 'not positive' for n in numbers]
print(labels)
Output
['not positive', 'not positive', 'positive']

For -2, the condition is false, so the expression produces 'not positive'. For 0, the condition is also false, so it produces 'not positive'. For 5, the condition is true, so it produces 'positive'. The result has three elements because the input contains three elements.

Note

A useful rule: put a filter after the iterable clause when you want to exclude items. Put an if-else conditional expression before the for clause when you want to choose a result value for each item.

5. Empty results, boundaries, and common patterns

A filtered comprehension can legitimately return an empty list. This is not an error; it means no input item satisfied the condition.

Boundary comparisons matter. The condition n > 0 excludes zero, while n >= 0 includes it. Likewise, len(word) > 4 excludes words with exactly four characters, while len(word) >= 4 includes them.

A filtered comprehension processes an iterable, not only a list. You can use tuples, strings, ranges, and other iterable objects. When the iterable is empty, there are no items to process.

Conditions can use comparisons, membership checks, string methods, and Boolean operators such as and and or. Keep conditions understandable, particularly when several requirements are combined.

A comprehension is useful when the transformation and filtering can be understood at a glance. If the logic requires several statements, nested branching, exception handling, or side effects, a regular for loop may be clearer.

No items match the condition

No items match the condition
python
numbers = [1, 3, 5, 7]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
Output
[]

Every number in the input is odd. No number passes the even-number filter. Python returns an empty list rather than raising an error.

Caution

Do not use a conditional expression when you intend to remove items, and do not use a filter when you need a replacement value for every item. Choose the form that matches the requirement.

6. Write readable comprehensions

A comprehension should make the result easier to understand, not merely shorten the code. Choose descriptive variable names and keep the expression and conditions simple.

For a straightforward task, such as selecting even numbers or converting selected words to uppercase, a comprehension is usually appropriate. If a reader must mentally evaluate many nested conditions or complicated expressions, use a regular loop instead.

The following loop and comprehension perform the same filtering task. Learning to translate between them helps you understand what a comprehension does rather than treating it as a special trick.

Equivalent for loop

Equivalent for loop
python
numbers = [1, 2, 3, 4, 5, 6]
evens = []
 
for n in numbers:
if n % 2 == 0:
evens.append(n)
 
print(evens)
Output
[2, 4, 6]

The loop visits each number. The if statement checks whether it is even. append adds only accepted values to the new list. A filtered comprehension expresses the same operation more compactly: evens = [n for n in numbers if n % 2 == 0].

Note

You should be able to explain a comprehension in plain language: where the values come from, which condition each value must satisfy, and what the result expression produces.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Putting the filter condition before the for clause in a basic filtered comprehension.

Why it happens: In a basic filtered comprehension, the for clause introduces each item and the trailing if filters it; putting the condition before for is invalid syntax.

Incorrect Approach
script.py
python
Putting the filter condition before the for clause in a basic filtered comprehension.
Correct Solution
script.py
python
Use the structure [expression for item in iterable if condition]. The filter follows the iterable clause.

Key takeaway: Use the structure [expression for item in iterable if condition]. The filter follows the iterable clause.

#2 Assuming that a filter replaces items that fail the condition.

Why it happens: A filter removes items that fail its condition rather than substituting another value for them.

Incorrect Approach
script.py
python
Assuming that a filter replaces items that fail the condition.
Correct Solution
script.py
python
A filter skips an item when its condition is false. Use an if-else conditional expression when you need a replacement value.

Key takeaway: A filter skips an item when its condition is false. Use an if-else conditional expression when you need a replacement value.

#3 Confusing the expression with the condition.

Why it happens: The expression determines the value produced for each included item, while the condition determines whether that item is included.

Incorrect Approach
script.py
python
Confusing the expression with the condition.
Correct Solution
script.py
python
In [n * 2 for n in numbers if n > 0], n * 2 determines the result value and n > 0 determines whether the item is included.

Key takeaway: In [n * 2 for n in numbers if n > 0], n * 2 determines the result value and n > 0 determines whether the item is included.

#4 Forgetting else in a conditional expression.

Why it happens: A conditional expression requires both if and else because it must choose a value for either outcome.

Incorrect Approach
script.py
python
Forgetting else in a conditional expression.
Correct Solution
script.py
python
Write both alternatives, as in 'yes' if condition else 'no'. A conditional expression requires an else branch.

Key takeaway: Write both alternatives, as in 'yes' if condition else 'no'. A conditional expression requires an else branch.

#5 Using > when the requirement includes the boundary value.

Why it happens: A strict > excludes the boundary; use >= when the exact threshold should also qualify.

Incorrect Approach
script.py
python
Using > when the requirement includes the boundary value.
Correct Solution
script.py
python
Check whether the requirement says greater than or greater than or equal to. Use > for a strict comparison and >= when equality should count.

Key takeaway: Check whether the requirement says greater than or greater than or equal to. Use > for a strict comparison and >= when equality should count.

#6 Expecting a filtered comprehension to always return at least one item.

Why it happens: If no input item passes the filter, the result is an empty list, which is a valid result.

Incorrect Approach
script.py
python
Expecting a filtered comprehension to always return at least one item.
Correct Solution
script.py
python
If no item satisfies the condition, the correct result is an empty list, [].

Key takeaway: If no item satisfies the condition, the correct result is an empty list, [].

#7 Writing a very complicated comprehension to avoid a normal loop.

Why it happens: Nested or multi-branch comprehensions can become difficult to read; a normal loop is often clearer for complex logic.

Incorrect Approach
script.py
python
Writing a very complicated comprehension to avoid a normal loop.
Correct Solution
script.py
python
Prefer a regular for loop when it makes multiple steps, branching, or complex logic easier to understand.

Key takeaway: Prefer a regular for loop when it makes multiple steps, branching, or complex logic easier to understand.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a filtered list comprehension in Python?
Answer:
It is a concise way to create a list from an iterable while including only items that satisfy a condition. For example, [n for n in numbers if n > 0] creates a list of positive numbers.
Q2:What is the difference between filtering and transforming in a list comprehension?
Answer:
Filtering determines which input items are included, while transforming determines the value produced for each accepted item. In [n * 2 for n in numbers if n > 0], n > 0 filters the input and n * 2 transforms the accepted values.
Q3:How does an if-else conditional expression differ from an if filter?
Answer:
An if filter excludes items whose condition is false. An if-else conditional expression chooses between two values for each processed item. For example, [n if n >= 0 else 0 for n in numbers] replaces negative values instead of removing their positions from the result.
Q4:What happens when no items satisfy a list comprehension's filter?
Answer:
The comprehension returns an empty list, []. This is a valid result and does not cause an error by itself.
Q5:Can a list comprehension have more than one filter condition?
Answer:
Yes. For example, [n for n in numbers if n > 0 if n % 2 == 0] applies two filters. The same requirement can be written with a combined condition: [n for n in numbers if n > 0 and n % 2 == 0].
Q6:When should you choose a regular for loop instead of a comprehension?
Answer:
Use a regular loop when the operation involves multiple steps, complex branching, exception handling, or side effects that would make a comprehension difficult to understand. Prefer the clearest structure for the task.

Key takeaways

  • The general filtered-comprehension syntax is [expression for item in iterable if condition].
  • The filter determines whether an item contributes to the result.
  • The expression before for determines the value added for an accepted item.
  • An if-else conditional expression chooses a value; it does not filter out the item.
  • A filter can produce an empty list when no items match.
  • Comparison operators determine whether boundary values are included.
  • Multiple filter conditions can be combined with and or written as successive if clauses.
  • Use comprehensions when they improve clarity and regular loops when they make complex logic easier to follow.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: