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.
Python code
4 linesnumbers = [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
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
- Use `filter` with a lambda: `list(filter(lambda x: x % 2 == 0, numbers))`
- 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
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.