How to filter even numbers with a Python list comprehension
Build a new list of only the even numbers from 1 to 20 using a single list comprehension with a filter condition.
Python code
2 lineseven_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
How it works
The list comprehension [num for num in range(1, 21) if num % 2 == 0] iterates over each integer in the range and includes num only when the condition num % 2 == 0 is True. The modulo operator % returns the remainder of division; an even number has remainder 0 when divided by 2. This pattern is concise and readable, replacing an explicit for loop with an append call. The result is a new list, leaving the original range unchanged.
Common mistakes
- Using `range(1, 21)` includes 1 to 20, not 1 to 21 — check the upper bound.
- Forgetting the `if` clause results in all numbers instead of only evens.
- Using `num / 2` instead of `num % 2` — the condition must test the remainder.
Variations
- Filter using `num % 2 != 0` for odd numbers.
- Use a generator expression `(num for num in range(1, 21) if num % 2 == 0)` for lazy evaluation.
Real-world use cases
- Filtering IDs or records that meet a parity condition before further processing in a data pipeline.
- Selecting even-indexed items from a list to split data into training and validation sets.
- Generating a list of valid port numbers (even ports) for a service configuration file.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.