Skip to content

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.

Beginner 10 min read·Lesson 146 of 306 in Python Programming

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

Python
passed = [m for m in marks if m >= 40] # filter
labels = ["pass" if m >= 40 else "fail" for m in marks] # choose
grades = ["A" if m >= 90 else "B" for m in marks if m >= 75] # both
  • Filter if: after for, no else.
  • Choice if/else: before for, needs else.

Code examples

Filtering

Python
marks = [72, 35, 88, 19, 91, 40]
print([m for m in marks if m >= 40])
words = ["apple", "", "kiwi", " ", "fig"]
print([w for w in words if w.strip()])
Output
[72, 88, 91, 40]
['apple', 'kiwi', 'fig']

Choosing a value

Python
marks = [72, 35, 88]
print(["pass" if m >= 40 else "fail" for m in marks])
print([n if n >= 0 else 0 for n in [5, -3, 2, -1]])
Output
['pass', 'fail', 'pass']
[5, 0, 2, 0]

More examples

Filter and transform together

Python
orders = [
{"id": 1, "amount": 1200, "paid": True},
{"id": 2, "amount": 300, "paid": False},
{"id": 3, "amount": 5400, "paid": True},
{"id": 4, "amount": 800, "paid": True},
]
big_paid_ids = [o["id"] for o in orders if o["paid"] if o["amount"] >= 1000]
print(big_paid_ids)
labels = [f"#{o['id']}:{'VIP' if o['amount'] > 5000 else 'regular'}" for o in orders if o["paid"]]
print(labels)
print(sum(o["amount"] for o in orders if not o["paid"]))
Output
[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:

TextOutput
[1, 3]
['#1:regular', '#3:VIP', '#4:regular']
300

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

[m for m in marks if m >= 40 else 0]

Prefer

[m if m >= 40 else 0 for m in marks]

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

valid = [x for x in data if x] # then indexing valid[i] like data[i]

Prefer

Keep indexes aligned by using a choice expression or enumerate.

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

  1. 1
    From a list of words, keep those longer than 4 letters and convert them to upper case.
  2. 2
    Replace 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?
Practise this topic