Sub topic 5
Transforming and selecting with map and filter
This chapter assumes you can write def functions and lambda expressions, and that you know lists, tuples, dictionaries and list comprehensions. You should also know that a function can be passed as an argument to another function. Here you will learn how map and filter work, what they return, and where they surprise people.
The idea behind both functions
map and filter are higher-order functions: they take a function as an argument. Each applies that function to every item of an iterable (anything you can loop over).
map(function, iterable)callsfunctionon each item and produces the results.filter(function, iterable)callsfunctionon each item and keeps the items for which the result is truthy.
map transforms items, so its output has the same length as its input. filter selects items, so its output can be shorter but never changes the items themselves.
caption: Data flows through filter first and then map, one item at a time.
alt: A flowchart from left to right. A list of numbers goes into filter, which keeps the even ones. The result goes into map, which squares each item. The final result is a new list of squares.
flowchart LR
A["nums: 1 2 3 4 5 6"] --> B["filter: keep even"]
B --> C["2 4 6"]
C --> D["map: square"]
D --> E["4 16 36"]map returns an iterator, not a list
In Python 3, map does not build a list. It returns a map object, which is an iterator. An iterator produces its values one at a time, only when something asks for them.
nums = [1, 2, 3, 4, 5, 6]
squares = map(lambda n: n * n, nums)
print(squares) # <map object at 0x...>
print(list(squares)) # [1, 4, 9, 16, 25, 36]
print(list(squares)) # []The second list(squares) prints an empty list. An iterator can be consumed only once. After the first list() call, nothing is left. If you need the values twice, store them in a list first, or create a new map object.
Iterators also lack list features:
squares = map(lambda n: n * n, [1, 2, 3])
try:
print(len(squares))
except TypeError as error:
print(error) # object of type 'map' has no len()
try:
print(squares[0])
except TypeError as error:
print(error) # 'map' object is not subscriptableConvert with list(), tuple() or set() when you need those features.
Laziness: work happens only on demand
Because map is lazy, the function is not called when you create the map object. It is called as values are requested.
def noisy(n):
print(f"processing {n}")
return n * 2
result = map(noisy, [1, 2, 3])
print("created")
print(next(result))The output is:
created
processing 1
2Only the first item has been processed. The other two have not. This is useful with large or infinite inputs, because you can stop early. It also has a consequence for side effects, covered below.
filter keeps items by truthiness
filter calls the function on each item. If the return value is truthy, the item is kept. The function's result does not have to be True or False.
words = ["apple", "", "fig", "", "pear"]
print(list(filter(lambda w: len(w) > 3, words))) # ['apple', 'pear']Like map, filter returns a lazy iterator, so it has the same one-pass behavior.
Passing None as the function
If the first argument is None, filter keeps the items that are truthy themselves:
words = ["apple", "", "fig", "", "pear"]
print(list(filter(None, words))) # ['apple', 'fig', 'pear']
mixed = [0, 1, "", "a", [], [0], None]
print(list(filter(None, mixed))) # [1, 'a', [0]]This is a quick way to drop empty strings and None values. It also drops 0, 0.0, empty lists and every other falsy value. If 0 is valid data in your list, use an explicit test such as lambda x: x is not None.
Combining the two
Because both functions accept and return iterables, they chain. This is the example from the plan of this tutorial:
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 nested call from the inside out. filter runs first and keeps 2, 4 and 6. map then squares those. Filtering before mapping means the transformation runs on fewer items. Nothing is computed until list() pulls the values through, and each item passes through both stages before the next item starts.
To keep a long chain readable, give each stage a name:
nums = [1, 2, 3, 4, 5, 6]
evens = filter(lambda n: n % 2 == 0, nums)
squares = map(lambda n: n * n, evens)
print(list(squares)) # [4, 16, 36]Both stages stay lazy, so naming them costs nothing.
Using named functions instead of lambdas
You do not need a lambda for every call. Any callable works, including built-in functions and methods. When one already does the job, it is shorter and often faster.
raw = ["12", "7", "x", "40"]
digits = filter(str.isdigit, raw)
numbers = map(int, digits)
print(list(numbers)) # [12, 7, 40]
names = ["ada", "grace", "linus"]
print(list(map(str.title, names))) # ['Ada', 'Grace', 'Linus']str.isdigit, int and str.title are used here as plain functions. str.title takes the string as its first argument, so map supplies each item correctly. Compare map(int, digits) with map(lambda s: int(s), digits). The lambda adds a layer that does nothing.
map with several iterables
If you pass more than one iterable, map takes one item from each per call. The function must accept that many arguments.
a = [1, 2, 3]
b = [10, 20, 30, 40]
print(list(map(lambda x, y: x + y, a, b))) # [11, 22, 33]The result has three items, not four. map stops when the shortest iterable runs out, and it does not warn you. The extra 40 is silently ignored. In Python 3.14 and later you can pass strict=True to raise a ValueError when the lengths differ. On older versions, check the lengths yourself if a mismatch would be a bug.
filter accepts only one iterable.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Printing a `map` object and expecting values | You see `<map object at ...>` | Wrap it in `list()` |
| Reusing an iterator | The second pass is empty | Store a list, or call `map` again |
| Calling `len()` or indexing | `TypeError` | Convert to a list first |
| `filter(None, data)` when `0` is valid | Zeros disappear | Use an explicit condition |
| Uneven input lengths in multi-iterable `map` | Extra items are dropped silently | Check lengths, or use `strict=True` on Python 3.14+ |
| Using `map` for side effects | Nothing runs | Use a `for` loop |
The side-effect trap
Since map is lazy, this line does nothing:
map(print, ["a", "b", "c"]) # prints nothingThe map object is created and discarded without ever being consumed. You could force it with list(map(print, items)), but that builds a useless list of None values. A plain loop states the intent better:
for item in ["a", "b", "c"]:
print(item)Reserve map for computing values, and write a loop for actions.
When to prefer which tool
The plan has a full chapter on comparing these with comprehensions, so only the short version appears here. map and filter read well when you pass an existing named function, as in map(int, strings). When you would need a lambda, a comprehension is usually shorter and easier to read. Their laziness is a real advantage when you want to process a large input one item at a time without building an intermediate list. A generator expression gives you the same laziness.
Exercise
Given data = ["3", "", "x", "10", "7"], write code that prints the sum of all entries that consist only of digits, using filter and map without any lambda. What does it print, and why is an empty string safe here?
Show answer
print(sum(map(int, filter(str.isdigit, data)))) prints 20. filter(str.isdigit, data) keeps "3", "10" and "7". map(int, ...) converts them to 3, 10 and 7, and sum adds them. The empty string is safe because "".isdigit() returns False, so filter drops it before int("") could raise a ValueError.
Exercise
What does this code print, and why? result = map(lambda n: n + 1, [1, 2, 3]) print(list(result)) print(sum(result))
Show answer
It prints [2, 3, 4] and then 0. The first list(result) consumes the iterator completely. The sum(result) call then sees an exhausted iterator with no items, so the sum is the starting value 0. To use the values twice, store them with values = list(result) first.
Exercise
What is the length of list(map(lambda x, y: x * y, [1, 2, 3], [4, 5])) on Python versions before 3.14, and what are its items?
Show answer
The length is 2 and the items are [4, 10]. map stops at the shortest iterable, so the third item of the first list is never used, and no error is raised.