Filter Items in Comprehensions
Core idea
Add a condition after the for clause: [expression for item in iterable if condition]. Only items satisfying the condition reach the result expression. A filter may shorten the list; it preserves the relative order of accepted items.
readings = [-3, 0, 4, -1, 7]print([n for n in readings if n >= 0])Zero is included because the condition is nonnegative, not strictly positive.
Filter before transforming
counts = [0, 3, 1, 0]print([12 // n for n in counts if n != 0])Zero never reaches the division expression.
Choose a result instead
values = [-2, 3, 0]print([n if n >= 0 else 0 for n in values])print([n for n in values if n >= 0])The expression a if condition else b chooses one value per item; a trailing if removes items.
Common mistake
Do not add else after a trailing filter. If each input needs a result, place a conditional expression before for instead.
Practice
Keep temperatures at least 10 from [8, 10, 15, 2], then double only those temperatures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Filter and transform
Check your understanding of comprehension filtering.
What is printed?
print([n for n in [-1, 0, 2] if n >= 0])What is printed?
print([12 // n for n in [0, 2] if n != 0])What is printed?
print([n if n > 0 else 0 for n in [-1, 2]])Where does a filter clause go?