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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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?
Q2:What is the difference between filtering and transforming in a list comprehension?
Q3:How does an if-else conditional expression differ from an if filter?
Q4:What happens when no items satisfy a list comprehension's filter?
Q5:Can a list comprehension have more than one filter condition?
Q6:When should you choose a regular for loop instead of a comprehension?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: