Advanced Python
Python `map()` and `filter()`
Overview
| Function | Purpose | Function must return |
|---|---|---|
map() |
Transform every element in an iterable | The new value for that element |
filter() |
Keep only elements that meet a condition | True (keep) or False (discard) |
Both return a special iterable object (not a list directly) — convert with list() if needed.
map()
Applies a function to every element of an iterable and returns a new iterable with the transformed values.
Syntax
map(function, iterable)
Basic Example — squaring values
lst = [1, 2, 3, 4, 5]
new_lst = list(map(lambda x: x ** 2, lst))
print(new_lst) # [1, 4, 9, 16, 25]
Using a named function instead of lambda
def square(x):
return x ** 2
new_lst = list(map(square, lst))
Other examples
import math
# Square roots
list(map(lambda x: math.sqrt(x), [1, 4, 9, 16])) # [1.0, 2.0, 3.0, 4.0]
# Sum of nested lists
lst = [[1, 2, 3], [4, 5, 6], [3, 3], [3, 4]]
list(map(lambda x: sum(x), lst)) # [6, 15, 6, 7]
The map object
result = map(lambda x: x ** 2, lst)
print(result) # <map object at 0x...> — not a list yet
print(list(result)) # [1, 4, 9, 16, 25]
# Can also loop through it directly without converting
for el in result:
print(el)
filter()
Keeps only elements for which the function returns True.
Syntax
filter(function, iterable)
Basic Example — keep nested lists with sum > 6
lst = [[1, 2, 3], [4, 5, 6], [3, 3], [3, 4]]
new_lst = list(filter(lambda x: sum(x) > 6, lst))
print(new_lst) # [[4, 5, 6], [3, 4]]
Other examples
# Keep lists with more than 2 elements
list(filter(lambda x: len(x) > 2, lst)) # [[1, 2, 3], [4, 5, 6]]
# Return True → keep all items
list(filter(lambda x: True, lst)) # all items kept
# Return False → keep nothing
list(filter(lambda x: False, lst)) # []
The filter object
result = filter(lambda x: sum(x) > 6, lst)
print(result) # <filter object at 0x...>
print(list(result)) # [[4, 5, 6], [3, 4]]
Using map() and filter() Together
Pass the result of map() directly into filter() (or vice versa):
lst = [[1, 2, 3], [4, 5, 6], [3, 3], [3, 4]]
# Step 1: map each sublist to its sum → [6, 15, 6, 7]
# Step 2: filter to keep only even sums → [6, 6]
new_lst = list(filter(
lambda y: y % 2 == 0,
map(lambda x: sum(x), lst)
))
print(new_lst) # [6, 6]
Step-by-step walkthrough:
1. map produces sums: [6, 15, 6, 7]
2. filter keeps only even values: 6 % 2 == 0 ✅, 15 % 2 == 0 ❌, 6 % 2 == 0 ✅, 7 % 2 == 0 ❌
3. Result: [6, 6]
Key Takeaways & Recap
| Concept | Summary |
|---|---|
map(fn, iterable) |
Applies fn to every element; returns a map object |
filter(fn, iterable) |
Keeps elements where fn returns True; returns a filter object |
| Return type | Both return iterable objects — wrap in list() to see contents |
| Best paired with | Lambda functions for concise inline logic |
| Can be chained | Pass map() output directly into filter() (or vice versa) |
| Named function works too | Any function with one parameter can replace the lambda |