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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

2 lines
Python 3.9+
even_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)

Output

stdout
[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

  1. Filter using `num % 2 != 0` for odd numbers.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.