Python · Chapter 41 of 45

map() & filter()

`map(func, seq)` applies func to every item. `filter(func, seq)` keeps items where func returns truthy.

Both return iterators — wrap in `list(...)` to see results.

Prefer comprehensions

`[f(x) for x in seq]` and `[x for x in seq if cond]` are usually clearer than map/filter.

With lambda

Map/filter commonly appear with a small lambda expression as the function.

Example 1 (python)
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x*2, nums))
print(doubled)
Output
[2, 4, 6, 8]

Double every number.

Example 2 (python)
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Output
[2, 4]

Keep only even numbers.

Key points

  • map transforms; filter selects.
  • Both return iterators (lazy).
  • Comprehensions are usually clearer.
  • Use with `list()` to materialise.
💡 Note: `list(map(int, ["1","2","3"]))` is a classic idiom to convert strings to ints.

📝 Quick Quiz

1. `filter(func, seq)` keeps items where:

2. The result of `map()` is:

3. Which is a Pythonic alternative to map?