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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

20 lines
Python 3.9+
def 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

stdout
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

  1. Use `lambda` functions inline: `[x*x for x in numbers if x % 2 == 0]` for quick one-off transformations.
  2. 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

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.