4 · Build useful programs · 9 MIN
Select matching items
Filtering keeps items that meet a rule.
A list comprehension builds a new list. [n for n in values if condition] keeps matching items in order. The % operator calculates a remainder. Filtering n values takes O(n) time and up to O(n) extra space.
A sieve keeps only the items that fit a rule.
Read the example
scores = [30, 60, 90] passed = [n for n in scores if n >= 60] print(passed)
Check the expected output
[60, 90]
Your challenge
Return a new list containing only the even numbers from input, preserving order.
Common trap
Use == to compare values; = assigns a value.
Next lesson: Describe a real thing →