Topic 61 of 64
Map, Filter, and Zip
Overview
map(), filter(), and zip() are built-in higher-order functions for transforming and combining iterables. They return lazy iterators — efficient for large datasets. In modern Python, list comprehensions are often preferred but these functions remain important for functional-style code and interop.
Syntax
python
nums = [1, 2, 3, 4, 5]
# map — transform each element
list(map(lambda x: x ** 2, nums)) # [1, 4, 9, 16, 25]
# filter — keep elements matching predicate
list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
# zip — combine iterables element-wise
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 72]
list(zip(names, scores))
# [('Alice', 95), ('Bob', 87), ('Charlie', 72)]
# Unzip
pairs = [("a", 1), ("b", 2), ("c", 3)]
keys, values = zip(*pairs)Common Pitfalls
- map() and filter() return iterators, not lists — wrap with list() to materialize, or iterate directly for memory efficiency.
- zip() stops at the shortest iterable — use itertools.zip_longest() to pad shorter ones.
- Interview tip: List comprehensions are generally preferred over map/filter in Python — they're more readable and slightly faster due to less function call overhead.
Real-World Example
Transform and filter API user objects for a response
example
python
users = [
{"name": "Alice", "age": 25, "active": True},
{"name": "Bob", "age": 16, "active": True},
{"name": "Charlie", "age": 30, "active": False},
]
# Get names of active adults
active_adults = list(
map(
lambda u: u["name"],
filter(lambda u: u["active"] and u["age"] >= 18, users)
)
)
# Or with list comprehension (more Pythonic):
active_adults = [u["name"] for u in users if u["active"] and u["age"] >= 18]
print(active_adults) # ['Alice']