Sub topic 6
Comprehensions or map and filter?
This chapter assumes you can write list comprehensions, read a lambda expression, and know that map and filter take a function and an iterable. You will compare the two styles, learn where they behave differently, and pick one for a given job.
Two ways to say the same thing
A transformation plus a condition can be written with map and filter or with one comprehension. Both produce the same values:
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 first version from the inside out. filter keeps the even numbers, then map squares them, then list collects the result. The comprehension reads in the order a sentence would: "n squared, for each n in nums, if n is even."
The comprehension needs no lambda and no list(...) wrapper. It also keeps the output expression, the loop variable and the condition in one place. That is why most Python style guides prefer comprehensions when you would otherwise write a lambda inside map or filter.
What each form returns
In Python 3, map and filter return lazy iterators. They do no work until something consumes them. A list comprehension builds the whole list immediately.
doubled = map(lambda n: n * 2, [1, 2, 3])
print(list(doubled)) # [2, 4, 6]
print(list(doubled)) # []The second list(doubled) is empty because an iterator is single-pass. The first call consumed it. This is a common source of bugs when you store a map object in a variable and use it twice. A list can be iterated as many times as you like and supports len(), indexing and slicing. A map object supports none of those.
| Feature | `map` / `filter` | List comprehension | Generator expression |
|---|---|---|---|
| Result type | Iterator | `list` | Iterator |
| Evaluation | Lazy | Eager | Lazy |
| Can be reused | No | Yes | No |
| Supports `len()` and indexing | No | Yes | No |
| Needs a function object | Yes | No | No |
Laziness is available to comprehensions too
Laziness is not a reason to prefer map. If you want it, change the square brackets to parentheses and you get a generator expression:
nums = [1, 2, 3, 4, 5, 6]
total = sum(n * n for n in nums if n % 2 == 0)
print(total) # 56No intermediate list is built. When a generator expression is the only argument to a call, you can drop the extra parentheses, as sum(...) does above. This pattern works well with sum, max, min, any, all and "".join.
Where map and filter read well
map and filter are not obsolete. They read well when you already have a named function and don't need a lambda.
raw = ["10", "20", "30"]
print(list(map(int, raw))) # [10, 20, 30]
print([int(s) for s in raw]) # [10, 20, 30]map(int, raw) is shorter than the comprehension and says exactly what it does. The same holds for map(str.strip, lines) or map(len, words). The rule of thumb is that map is clean when its first argument is an existing function and awkward when it is a lambda.
filter has a special form. Passing None as the function keeps only the truthy items:
values = [0, 1, "", "a", None, [], [2]]
print(list(filter(None, values))) # [1, 'a', [2]]The comprehension equivalent is [v for v in values if v]. Both are fine. Keep in mind that 0, "", None and empty containers are all dropped. If 0 is valid data in your list, use an explicit condition such as v is not None.
Edge cases that change the answer
Several iterables at once
map accepts more than one iterable and passes one item from each to the function. It stops when the shortest iterable runs out.
a = [1, 2, 3]
b = [10, 20]
print(list(map(lambda x, y: x + y, a, b))) # [11, 22]
print([x + y for x, y in zip(a, b)]) # [11, 22]With operator.add instead of a lambda, map(add, a, b) is concise. When you need a lambda here, the zip comprehension is usually easier to read. Both silently drop the extra item 3. If a length mismatch should be an error, use zip(a, b, strict=True) (Python 3.10 and later) in the comprehension. map accepts the same strict=True keyword only from Python 3.14.
Nested loops and multiple conditions
Comprehensions can contain several for clauses and several if clauses. Expressing the same logic with map and filter needs extra layers.
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
print(pairs)
# [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]A map/filter version needs itertools.product plus a lambda that unpacks the tuple. It gives you nothing in return. Once a comprehension has more than two clauses, though, consider a def or a plain loop instead (see the last section).
Producing dictionaries and sets
Only comprehensions have dedicated forms for these:
words = ["apple", "fig", "pear"]
lengths = {w: len(w) for w in words}
initials = {w[0] for w in words}
print(lengths) # {'apple': 5, 'fig': 3, 'pear': 4}
print(sorted(initials)) # ['a', 'f', 'p']With map you would have to build a list of pairs and wrap it in dict(...).
Calling an expensive function once
A comprehension that both transforms and filters on the transformed value tempts you to call the function twice:
def parse(text):
return int(text) if text.isdigit() else None
data = ["4", "x", "7"]
# parse() runs twice for each valid item
slow = [parse(t) for t in data if parse(t) is not None]
# parse() runs once per item (needs Python 3.8+)
fast = [n for t in data if (n := parse(t)) is not None]
print(slow, fast) # [4, 7] [4, 7]The assignment expression := stores the result so the output expression can reuse it. A map followed by a filter also calls the function once per item, which is one of the few places the two-step pipeline does better than a naive comprehension.
Performance
Speed rarely decides this. Two things are worth knowing:
map(len, items)with a built-in function is often a little faster than the equivalent comprehension, because the loop runs in C with no Python-level expression to evaluate.map(lambda ...)is usually slower than a comprehension, because every item pays for a Python function call. A comprehension evaluates its expression inline.
Deciding
In practice:
- If the first argument to
maporfilterwould be alambda, write a comprehension. - If you have a named function that takes one argument, such as
int,str.striporlen,mapis a clean choice. - If you need a
dictorset, use the matching comprehension. - If you will only loop over the result once, or feed it to
sum,maxorany, use a generator expression and skip the list. - If you need to read the result twice, or take its length, produce a list.
Exercise
The code below prints a list, then prints an empty list. Why, and how do you fix it so both lines show the squares? Also rewrite the pipeline as a comprehension. squares = map(lambda n: n * n, [1, 2, 3]) print(list(squares)) print(list(squares))
Show answer
map returns a single-pass iterator. The first list(squares) consumes it, so the second call finds nothing left and returns []. Fix it by storing a list: squares = [n * n for n in [1, 2, 3]], which can be printed any number of times. If you want to keep map, wrap it once, squares = list(map(lambda n: n * n, [1, 2, 3])). The comprehension form is [n * n for n in [1, 2, 3]].