How to Combine filter and map with a List Comprehension in Python
This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.
Python code
20 linesdef square(x):
return x * x
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = [square(x) for x in numbers if is_even(x)]
print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")
# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapped = map(square, filtered)
equivalent = list(mapped)
print(f"Using filter+map: {equivalent}")
print(f"Are they equal? {result == equivalent}")
Output
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8]
Squares of even numbers: [4, 16, 36, 64]
Using filter+map: [4, 16, 36, 64]
Are they equal? True
How it works
The list comprehension [square(x) for x in numbers if is_even(x)] iterates over each element, checks is_even(x), and if true, appends square(x) to the result. This combines filtering and mapping in one readable line. The filter(is_even, numbers) call returns an iterator of even numbers, then map(square, filtered) applies square to each, and list() materializes the result. Both approaches produce identical lists, demonstrating that the comprehension is a concise, Pythonic replacement for nested function calls.
Common mistakes
- Forgetting parentheses when chaining filter() and map(), causing arguments to be passed incorrectly.
- Assuming the order of conditions and expressions in a comprehension is interchangable - the condition must come after the loop part.
- Using `filter` and `map` with list comprehensions unnecessarily when the comprehension is clearer.
Variations
- Use `lambda` functions inline: `[x*x for x in numbers if x % 2 == 0]` for quick one-off transformations.
- Use generator expressions for lazy evaluation: `(square(x) for x in numbers if is_even(x))` and then iterate or convert to a list.
Real-world use cases
- Building a list of square prices for items that are in stock and discounted in an e-commerce API.
- Transforming and filtering log entries to extract only error lines and format them in a summary report.
- Preprocessing sensor readings by filtering out invalid values and applying a normalization function before analysis.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.