A program selects only passing exam scores.
What You Need to Understand
A conditional list comprehension can filter values using a trailing if clause. An inline conditional expression before for chooses an output for every item instead of removing items.
When to Use It
A program selects only passing exam scores.
Step-by-Step Python Example
scores = [42, 81, 59, 93]
passing = [score for score in scores if score >= 60]
labels = ["pass" if score >= 60 else "retry" for score in scores]
print(passing)
print(labels)
How the Example Works
The first result contains only scores 81 and 93. The second contains four labels because no score is filtered out.
Example Output
[81, 93]
['retry', 'pass', 'retry', 'pass']
[2, 4]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
numbers = [1, 2, 3, 4]
print([number for number in numbers if number % 2 == 0])
Important Behavior and Edge Cases
Do not confuse the filter form [x for x in values if condition] with the conditional expression form [a if condition else b for x in values].
Try It Yourself
Filter even numbers and then label all numbers as even or odd.
Common Beginner Mistakes
- Do not confuse the filter form
[x for x in values if condition]with the conditional expression form[a if condition else b for x in values]. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- A conditional list comprehension can filter values using a trailing
ifclause. - The first result contains only scores 81 and 93.
- Do not confuse the filter form
[x for x in values if condition]with the conditional expression form[a if condition else b for x in values].