Filtered comprehension
- Python course
- Beginner
- Lesson 60/116
- 5 min
Learn filtered comprehensions with [x for x in xs if cond].
Filtered comprehension
You can filter items by adding an if condition to the comprehension:
evens = [n for n in [1, 2, 3, 4] if n % 2 == 0]
# [2, 4]The shape is: [expression for variable in list if condition]. Only items whose condition is True stay in the result. The condition is evaluated for each item.
Filtering is shorter than using an if inside a loop to append items.
Multiple conditions
You can combine multiple conditions with and or or:
result = [n for n in range(20) if n % 2 == 0 and n % 3 == 0]
# [0, 6, 12, 18]Both conditions must be True. This shows that any filtering a loop can do, a comprehension can do too.
Practice Filter positive numbers
Assign to positives a comprehension that selects items greater than zero from [-3, -1, 0, 2, 5]. Then print print(positives).
Starter code
# Filter positive itemsSample solution
positives = [n for n in [-3, -1, 0, 2, 5] if n > 0]
print(positives)Expected output
[2, 5]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Filter even numbers
evens = [n for n in [1, 2, 3, 4] if n % ____ == 0]
evens = [n for n in [1, 2, 3, 4] if n % 2 == 0]
Explanation: n % 2 == 0 selects even numbers.
2 Match the filter parts
| Term | Meaning |
|---|---|
if |
Filter keyword |
n % 2 == 0 |
Even number condition |
and |
And connector |
or |
Or connector |
3 What does [n for n in [1, 2, 3, 4, 5] if n > 3] produce?
- [1, 2, 3]
- [4, 5] Correct answer
- [3, 4, 5]
- [1, 2]
Explanation: The condition n > 3 keeps only 4 and 5.