Sub topic 5
Transforming and selecting with map and filter
This chapter assumes you can define functions with def, work with lists and tuples, read list comprehensions, and use lambda expressions as shown in earlier chapters. It covers map and filter, two built-in higher-order functions that take a function as their first argument.
What map and filter do
map(func, iterable) applies func to every item and produces the results. filter(func, iterable) keeps only the items for which func returns a true value.
Both return lazy iterators in Python 3. They do not build a list until you ask for one, for example with list().
| Function | Question it answers | Output length |
|---|---|---|
| `map(f, items)` | What is `f(item)` for each item? | Same as the input |
| `filter(f, items)` | Which items satisfy `f`? | Equal to or shorter than the input |
Combining them
The next example keeps the even numbers, then squares them. Both steps use lambdas. The same result is built with a list comprehension so you can compare the two.
nums = [1, 2, 3, 4, 5, 6]
via_hof = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
via_comp = [n * n for n in nums if n % 2 == 0]
print(via_hof) # [4, 16, 36]
print(via_comp) # [4, 16, 36]Read the map and filter version from the inside out. filter runs first and passes the even numbers to map. The comprehension states the same two steps in reading order: the expression, then the loop, then the condition.
Laziness and common errors
Because the results are lazy, a map object behaves differently from a list.
squares = map(lambda n: n * n, [1, 2, 3])
print(list(squares)) # [1, 4, 9]
print(list(squares)) # []The first list() call consumes the iterator. The second finds nothing left. If you need the results more than once, store them in a list first.
Laziness also delays side effects and errors. A function with a bug does not fail when you call map. It fails when something first reads the results.
def parse(text):
return int(text)
results = map(parse, ["1", "2", "x"]) # no error yet
print(next(results)) # 1
print(next(results)) # 2
# next(results) would now raise ValueErrorAnother frequent mistake is passing None to filter without knowing what it does. filter(None, items) keeps only truthy items, so it also drops 0, "" and empty lists.
values = [0, 1, "", "a", [], [2]]
print(list(filter(None, values))) # [1, 'a', [2]]A third point: map accepts several iterables when the function takes several arguments. It stops at the shortest one.
print(list(map(lambda a, b: a + b, [1, 2, 3], [10, 20]))) # [11, 22]When to prefer which
map and filter read well when you already have a named function. map(str.upper, words) and filter(str.isdigit, tokens) need no lambda and are short. Once you must write a lambda, a comprehension is usually clearer, because it avoids the extra lambda keyword and the nested calls. Comprehensions also let you combine the transform and the condition in one place.
Exercise
What does list(filter(lambda s: len(s) > 2, ["ab", "abc", "", "abcd"])) return, and how would you write it as a list comprehension?
Show answer
It returns ['abc', 'abcd'], because only those strings have more than two characters. The comprehension is [s for s in ["ab", "abc", "", "abcd"] if len(s) > 2].
Exercise
Why does the second list(squares) call in the laziness example print an empty list?
Show answer
map returns an iterator, and the first list() call consumes it. An exhausted iterator yields no more items, so the second call produces [].