List Comprehension to Filter Even Numbers in Python

Creates a new list containing only the even numbers from an existing list using a list comprehension with a condition.

Easy Python 3.6+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

4 lines
Python 3.6+
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(f"Original: {numbers}")
print(f"Even numbers: {even_numbers}")

Output

stdout
Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers: [2, 4, 6, 8, 10]

How it works

The list comprehension [n for n in numbers if n % 2 == 0] iterates over each element in numbers, evaluates the condition n % 2 == 0, and only includes elements that evaluate to True. The modulo operator % returns the remainder of division, so even numbers have a remainder of 0 when divided by 2. This creates a new list without modifying the original, preserving the original data. The f-string print statements format the output cleanly for display.

Common mistakes

  • Using `if` before the `for` clause instead of after, which causes a syntax error
  • Mutating the original list while iterating, leading to unexpected results
  • Using `n % 2` (truthy for 1,2,3...) as a condition instead of `n % 2 == 0`

Variations

  1. Use `filter` with a lambda: `list(filter(lambda x: x % 2 == 0, numbers))`
  2. Use a generator expression for lazy processing: `(n for n in numbers if n % 2 == 0)`

Real-world use cases

  • Filtering valid transaction IDs where the last digit is even for a business rule.
  • Selecting rows from a log file where a metric count is even for reporting.
  • Extracting even-indexed items during data preprocessing for sampling.

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.