Sub topic 6
Comprehensions or map and filter?
This chapter assumes you can write list comprehensions, and that you know how to write a lambda and what map and filter do.
Same result, two styles
Both snippets below square the even numbers in a list.
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]The comprehension reads left to right: the value, the source, then the condition. The map and filter version reads from the inside out. You find filter first, then work back out to map. Each lambda also adds a function call for every item.
Most Python style guides prefer the comprehension when the work needs a lambda.
When map and filter read well
If you already have a named function, map is short and clear. There is no lambda to read.
raw = ["10", "20", "30"]
numbers = list(map(int, raw))
print(numbers) # [10, 20, 30]
words = ["a", "", "b", ""]
non_empty = list(filter(None, words))
print(non_empty) # ['a', 'b']Passing None to filter keeps only truthy items. The comprehension equivalents, [int(s) for s in raw] and [w for w in words if w], are also fine. Choose whichever your team finds easier to read.
Laziness: a real difference
In Python 3, map and filter return iterators. They produce values on demand, and you can only consume them once.
nums = [1, 2, 3]
squares = map(lambda n: n * n, nums)
print(list(squares)) # [1, 4, 9]
print(list(squares)) # []The second list(squares) is empty because the iterator is already used up. A list comprehension builds a list that you can reuse. To keep the laziness with comprehension syntax, use a generator expression with parentheses:
nums = [1, 2, 3, 4]
lazy = (n * n for n in nums if n % 2 == 0)
print(sum(lazy)) # 20Laziness helps with large or endless data, because you never hold the whole result in memory. It also causes the exhausted-iterator bug above.
What comprehensions can do that map and filter cannot
Comprehensions can build sets and dictionaries, and they can use several loops in one expression.
names = ["ana", "bo", "cy"]
lengths = {name: len(name) for name in names}
print(lengths) # {'ana': 3, 'bo': 2, 'cy': 2}
pairs = [(x, y) for x in range(2) for y in range(2)]
print(pairs) # [(0, 0), (0, 1), (1, 0), (1, 1)]With map and filter you would have to build the dictionary or the nested loop by hand.
Quick comparison
| Situation | Better choice |
|---|---|
| Transform and filter in one pass | Comprehension |
| Apply an existing function such as `int` or `str.strip` | `map` or a comprehension |
| The step would need a lambda | Comprehension |
| Build a dict or set | Dict or set comprehension |
| Large or endless data, one pass | Generator expression, or `map`/`filter` |
| Multiple loops | Comprehension |
Common errors
- Printing a
mapobject and getting<map object at ...>instead of values. Convert it withlist(). - Nesting several
mapandfiltercalls until the line is hard to read. Switch to a comprehension or split the steps into named variables. - Using a comprehension for side effects, such as
[print(x) for x in items]. That builds a throwaway list. Use a plainforloop.
Exercise
You have data = ["3", "x", "7", "", "5"]. Using a comprehension, produce a list of the integers for entries that consist only of digits (the list [3, 7, 5]). Then say why map(int, data) alone would fail.
Show answer
[int(s) for s in data if s.isdigit()] gives [3, 7, 5]. The isdigit() test drops "x" and the empty string. map(int, data) would fail with a ValueError when it reaches "x", because it tries to convert every item and has no filtering step. Since map is lazy, the error only appears when you consume the iterator, for example with list().