Filter Even Numbers Practice Problem
This data science coding problem helps you practice List & Dict Comprehensions, filter even numbers, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of List & Dict Comprehensions.
- Problem ID: 91
- Problem key: 91-filter-even-numbers
- URL: https://datacrack.app/solve/91-filter-even-numbers
- Difficulty: easy
- Topic: List & Dict Comprehensions
- Module: Python Fundamentals
Problem Statement
# 🧩 Filter Even Numbers
---
### 🎯 Goal
List comprehensions are one of Python's most beloved features — they let you write concise, readable transformations and filters in a single line. This problem introduces the **filter comprehension** pattern, the foundation of `.loc[]`, `filter()`, and boolean masking.
---
### 🔍 List Comprehension Syntax
```python
# Loop version
result = []
for x in numbers:
if x % 2 == 0:
result.append(x)
# Comprehension version — same logic, one line
result = [x for x in numbers if x % 2 == 0]
```
The pattern: `[expression for item in iterable if condition]`
---
### 💻 Task
Implement `filter_even(numbers)` using a **list comprehension** (one line inside the function).
---
### 📥 Input
- `numbers`: list of integers
### 📤 Output
- A list of only the even numbers from `numbers`, in original order
---
### 🧩 Starter Code
```python
def filter_even(numbers):
"""
Return only the even numbers from the list using a list comprehension.
Args:
numbers (list[int]): Input list
Returns:
list[int]: Even numbers only
"""
# 🧠 TODO: Use a list comprehension with an `if` condition for even numbers
pass
```
---
### 💡 Example
```python
filter_even([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Expected: [2, 4, 6, 8, 10]
filter_even([0, -2, -3, 4])
# Expected: [0, -2, 4]
```
---
### 🔑 Key Concepts
- `x % 2 == 0` — even number check (modulo 2 equals 0)
- 0 is even
- Negative even numbers (-2, -4) should be includedStarter Code
def filter_even(numbers):
"""
Return only the even numbers from the list using a list comprehension.
Args:
numbers (list[int]): Input list
Returns:
list[int]: Even numbers only
"""
# 🧠 TODO: Use a list comprehension with an `if` condition for even numbers
pass