Module 10 · Comprehensions and Advanced Iteration — topic 2 of 13
Conditional comprehensions
Filtering items with an if clause, transforming items differently with a conditional expression, and combining both in one comprehension.
Learning objectives
- Filter items with a trailing if clause
- Choose values with a conditional expression
- Tell the two forms apart by their position
Definition
A conditional comprehension adds an if clause after the for clause ([x for x in items if test]) to keep only items for which the test is true; a conditional expression in the output part (a if test else b) chooses the value for each item.
Introduction
Comprehensions can also select: [m for m in marks if m >= 40] keeps only passing marks. And they can choose: ['pass' if m >= 40 else 'fail' for m in marks] labels every mark.
Why it matters
Filtering and labelling are among the most common data-processing tasks. Getting the syntax right — where the if goes — is a frequent beginner stumbling block.
Detailed explanation
Filter form: [expression for item in iterable if condition]. The if comes after the for, has no else, and decides whether an item is included. The result can be shorter than the input.
Choice form: [a if condition else b for item in iterable]. The conditional expression comes before the for, must have an else, and the result has one element per input item.
Both can be combined: ['A' if m >= 90 else 'B' for m in marks if m >= 75] first filters, then labels.
Several if clauses may follow; they are combined with and: [x for x in nums if x > 0 if x % 2 == 0].
This is the comprehension equivalent of filter() and map(), usually more readable than those functions with lambdas.
Syntax
- Filter if: after for, no else.
- Choice if/else: before for, needs else.
Code examples
Filtering
[72, 88, 91, 40] ['apple', 'kiwi', 'fig']
Choosing a value
['pass', 'fail', 'pass'] [5, 0, 2, 0]
More examples
Filter and transform together
[1, 3] ['#1:regular', '#3:VIP', '#4:regular'] 300
Step-by-step explanation
- Two trailing if clauses mean paid and amount >= 1000.
- The second comprehension filters paid orders, then uses a conditional expression inside an f-string to label each one.
- The last line passes a generator expression to sum to total the unpaid amounts.
Expected output
Running “Filter and transform together” prints exactly:
Practical applications
- Selecting active users, valid rows or in-stock products.
- Replacing missing values: [v if v is not None else 0 for v in data].
Best practices
- Put filters at the end and choices at the start.
- Keep conditions simple; extract a helper function for complex tests.
- Use sum/any/all with generator expressions for totals and checks.
Common mistakes
else in the filter position
Avoid
Prefer
A trailing if is a filter and can't have else; to choose a value, put the conditional expression before for.
Expecting a filter to keep length
Avoid
Prefer
Filtering removes items, so positions change.
Important notes
- any(x > 100 for x in data) and all(...) are often what you really need instead of building a filtered list.
Key takeaways
- Trailing if filters items (no else).
- Leading a if c else b chooses values (needs else).
- They can be combined in one comprehension.
Try it yourself
- 1From a list of words, keep those longer than 4 letters and convert them to upper case.
- 2Replace every negative temperature reading with None using a conditional expression.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?