map and filter
🌍 In real life. On a factory line, one machine stamps a logo on every bottle that passes (that's map), and a second machine pushes off any bottle that's cracked (that's filter). Neither machine cares what the bottles are for; you just tell it the one job to do to each.
The idea in one sentence: map(f, items) calls f on every item, and filter(f, items) keeps only the items where f gives True; both hand back results one at a time.
Its words:
map(f, items): transform every itemfilter(f, items): keep the items that pass a test- lazy: the results are made only as you ask for them;
list(...)asks for all of them
Step by step, for list(map(lambda n: n * 2, [1, 2, 3])):
mapgets ready but does nothing yet.listasks for the results: 1 → 2, 2 → 4, 3 → 6.- The result is
[2, 4, 6].
nums = [1, 2, 3]
doubled = list(map(lambda n: n * 2, nums))
print(doubled)
words = ["7", "42", "5"]
print(list(map(int, words)))evens = list(filter(lambda n: n % 2 == 0, range(1, 7)))
print(evens)
words = ["a", "tea", "pot", "it"]
print(list(filter(lambda w: len(w) > 2, words)))Anything map and filter do, a list comprehension can do too, and Python programmers often find the comprehension easier to read. map is handy with a function that already exists, like int: list(map(int, input().split())) reads a line of numbers.
nums = [1, 2, 3, 4]
print(list(map(lambda n: n * n, nums)))
print([n * n for n in nums])
print(list(filter(lambda n: n > 2, nums)))
print([n for n in nums if n > 2])What it costs. Both are one pass over the items, like a comprehension. Being lazy means map and filter use almost no memory until you ask for the results; that matters later for huge inputs (Chapter 26).
Mistakes and edge cases.
- Printing the map itself.
print(map(int, ["1"]))shows<map object at 0x...>. Wrap it inlist(...). - Using it twice. A map or filter is used up after one pass:
list(m)thenlist(m)again gives[]the second time. - Errors appear late.
map(int, ["1", "a"])doesn't fail when it's made, only whenlist(...)reaches "a":ValueError: invalid literal for int() with base 10: 'a'. - The arguments' order. It's
map(function, items), function first.
Quiz
What does this print?
print(list(map(len, ["hi", "tea", ""])))What does this print?
print(list(filter(lambda n: n > 2, [5, 1, 3, 2])))What does this print?
print(list(map(str, [1, 2])))What does
print(map(int, ["1", "2"]))show?- Something like <map object at ...>, not the numbers
- [1, 2]
- An error
Which line has a mistake?
nums = [1, 2, 3] big = filter(lambda n: n > 1, nums) print(big[0])
Coding tasks
Read one line of whole numbers separated by spaces and print their sum. Use
mapto turn them into numbers.Write
lengths(words)that returns a list of the words' lengths, usingmap.Write
positives(nums)that returns a list of only the numbers greater than 0, usingfilter.