Python Map and Filter: Examples, Lazy Gotchas and List Comprehension Timings
Python map applies a function to every item, and filter keeps only the items that pass a test. Learn how both work, why they return lazy iterators, how to chain them, and when a list comprehension is faster, with timings we measured.
- Python map calls a function on every item; filter keeps items where the function returns a truthy value.
- Both return lazy iterators. Our map object gave a full list once and an empty list the second time.
- With a lambda, a list comprehension was faster in our test: 66.8 ms vs 117.9 ms for a million items.
- With a built-in like
str, map was the faster one: 134.8 ms vs 147.8 ms.
You have a list of prices and need them with tax added, or a list of user records and only want the active ones. Python gives you two built-in tools for exactly this: map transforms each item, and filter drops the items you do not want. They need no import, they work on any iterable, and they show up everywhere from data cleaning scripts to test helpers.
This guide walks through both functions with small examples you can paste into a terminal. Every output below came from a real run on Python 3.13.6. We also timed map and filter against list comprehensions, because the honest answer to “which is faster” depends on the function you pass in.
What map and filter do
Both functions take a function and an iterable. The difference is what they do with the function’s result:
| Function | Calls your function on | Keeps | Output length |
|---|---|---|---|
map(func, it) |
every item | the return value | same as input (shortest input if several) |
filter(func, it) |
every item | the original item, if the result is truthy | same or shorter |
So map changes values but not the count, and filter changes the count but not the values. Keeping that one sentence in mind prevents most confusion. If you are new to small inline functions, our Python lambda functions guide covers the syntax used in the examples.
Python map basics
Pass the function itself, without parentheses, followed by the iterable. Here we square numbers and upper-case strings:
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * n, nums)))
print(list(map(str.upper, ["api", "sql", "git"])))
[1, 4, 9, 16, 25, 36]
['API', 'SQL', 'GIT']
The second line shows a pattern worth copying: you do not need a lambda when a method or built-in already does the job. str.upper, int, float, len and round all work directly. A classic one-liner turns a line of space-separated input into a sum:
print(sum(map(int, "1 2 3 4".split()))) # 10
Map objects are lazy, and you can only read them once
In Python 3, map does not build a list. It returns a map object, an iterator that computes each value only when you ask for it. That saves memory on big inputs, but it surprises people the first time:
sq = map(lambda n: n * n, nums)
print(sq)
print(list(sq))
print(list(sq))
<map object at 0x0000018786854280>
[1, 4, 9, 16, 25, 36]
[]
Printing the object shows only its type and memory address. The first list() consumes it, so the second one gets nothing. Filter objects behave the same way. If you need the results twice, convert to a list once and reuse the list. This is the same behaviour as generators, which our Python generators guide explains in depth.
Tip: when a test or a loop mysteriously sees an empty result, check whether a map or filter object was already consumed earlier, for example by a debug print(list(...)) line.
Using map with two or more lists
Give map a function that takes several arguments and pass one iterable per argument. Items are paired by position, much like zip:
print(list(map(lambda a, b: a * b, [1, 2, 3], [10, 20, 30, 40])))
[10, 40, 90]
Notice that the fourth value, 40, was silently ignored. Map stops at the shortest iterable and raises no warning. If unequal lengths would be a bug in your program, check the lengths first, or use zip(a, b, strict=True) with a comprehension so Python raises an error. Our Python zip guide shows that strict mode in action.
Python filter basics
Filter calls your function on each item and keeps the item when the result is truthy. The classic example keeps even numbers:
print(list(filter(lambda n: n % 2 == 0, nums)))
[2, 4, 6]
The function you pass is often called a predicate: something that answers yes or no. It does not have to return exactly True or False. Any truthy value keeps the item, and any falsy value (0, empty string, None, empty list) drops it. That leads to a handy shortcut.
filter(None): drop all falsy values
If you pass None instead of a function, filter keeps only the items that are truthy themselves:
print(list(filter(None, [0, 1, "", "qa", None, [], [0]])))
[1, 'qa', [0]]
This is a quick way to clean blank strings out of a split line or remove empty rows from a CSV. Be careful with numbers, though: 0 is falsy, so a legitimate zero disappears too. In our output, the list [0] survived because a non-empty list is truthy even when it contains a zero. When zeros matter, write an explicit test such as lambda x: x is not None.
Chaining map and filter
Because both return iterators, you can feed one into the other. Here we keep prices above 10, add 18% tax, and round:
prices = {"pen": 1.5, "book": 12.0, "bag": 40.0}
print(list(map(round, map(lambda p: p * 1.18, filter(lambda p: p > 10, prices.values())))))
[14, 47]
It works, but it reads inside out: you have to start from the right to follow it. Filtering first is the right order, because it means the tax lambda only runs on the items you keep. Once a chain needs more than two steps, a comprehension or named intermediate variables usually read better:
expensive = [p for p in prices.values() if p > 10]
with_tax = [round(p * 1.18) for p in expensive]
Map and filter vs list comprehensions
Almost every map or filter call has a list comprehension equivalent:
| Goal | map / filter | Comprehension |
|---|---|---|
| Transform | list(map(f, xs)) |
[f(x) for x in xs] |
| Keep some | list(filter(p, xs)) |
[x for x in xs if p(x)] |
| Both | list(map(f, filter(p, xs))) |
[f(x) for x in xs if p(x)] |
| Lazy version | map(f, xs) |
(f(x) for x in xs) |
Comprehensions put the expression inline, so you never need a lambda, and the transform and the condition sit in one readable line. Map shines when you already have a named function, because map(str.strip, lines) is shorter than the comprehension and just as clear. Our Python list comprehension guide covers nested and dictionary comprehensions too.
Speed: what we measured
We timed each approach on a list of one million integers with timeit, taking the best of three repeats of five runs each. Times are per run on one Windows laptop with Python 3.13.6:
| Task | map / filter | List comprehension | Faster |
|---|---|---|---|
| Double each number (lambda) | 117.9 ms | 66.8 ms | Comprehension |
Convert to string (built-in str) |
134.8 ms | 147.8 ms | map |
| Keep odd numbers (lambda) | 81.7 ms | 54.4 ms | Comprehension |
The pattern is consistent with how CPython works. Calling a lambda is a full Python function call for every item, while a comprehension evaluates x * 2 inline without that call. When the function is a built-in written in C, such as str, map avoids a small amount of loop overhead and wins by about 9%. Your numbers will differ by machine, but the direction is what matters: use a comprehension instead of map with a lambda, and do not be afraid of map with a built-in.
For most code these differences are tiny compared with I/O or database calls. Choose the version your team reads fastest, and only optimise a hot loop after measuring it.
Where reduce fits
Tutorials often teach map, filter and reduce together. Reduce combines all items into one value, and it moved to the functools module in Python 3:
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4])) # 10
For sums, use sum(); for the largest item, max(); for joining strings, "".join(). Reduce is still useful for things like merging a list of dictionaries, and our Python functools guide covers it alongside partial and lru_cache.
starmap for lists of tuples
If your data is already grouped into tuples, itertools.starmap unpacks each tuple into arguments, which plain map cannot do:
import itertools
print(list(itertools.starmap(pow, [(2, 3), (3, 2)]))) # [8, 9]
That is equivalent to [pow(a, b) for a, b in pairs]. See our Python itertools guide for more tools that work well with map and filter.
Lazy evaluation delays errors
Because map does no work until you consume it, an exception appears later than you might expect. We created a map that divides by zero:
g = map(lambda x: 1 / x, [1, 0])
print("created ok")
try:
list(g)
except ZeroDivisionError as e:
print("ZeroDivisionError at list():", e)
created ok
ZeroDivisionError at list(): division by zero
Creating the map succeeded. The error only fired when list() pulled the second value. In real code, the consuming line might be in another function or module, which makes the traceback confusing. When debugging, convert to a list right where you build the map so errors point at the right place.
Which one should you choose?
- Use map when you apply an existing named function:
map(int, parts),map(str.strip, lines). - Use filter with an existing predicate, such as
filter(str.isdigit, tokens), orfilter(None, items)to drop blanks. - Use a comprehension when you would otherwise write a lambda, or when you transform and filter at once.
- Use a generator expression instead of a list when the data is large and you only loop over it once.
- Use a plain for loop when each item needs several steps, logging or error handling.
Common mistakes
- Calling the function:
map(int(), parts)passes 0, not the function, and the TypeError only appears once the map is consumed. Writemap(int, parts). - Reusing an iterator: looping over the same map or filter object twice gives nothing the second time.
- Expecting a list:
len(map(...))raises a TypeError, because map objects have no length. - Losing zeros:
filter(None, ...)removes0and0.0as well as blanks. - Silent truncation: map with two lists of different lengths quietly drops the extra items.
- Side effects in map: using map just to call
printdoes nothing until consumed. Use a for loop for side effects.
Final thoughts
Python map and filter are small, fast and expressive once you remember that they return lazy, single-use iterators. Pair them with named functions and built-ins, reach for a list comprehension whenever you would need a lambda, and convert to a list when you need the results more than once. Our timings showed comprehensions winning with lambdas and map winning with a C built-in, so let readability decide the rest.
Frequently asked questions
What does map return in Python 3?
It returns a map object, which is a lazy iterator. Wrap it in list() or tuple() to see the values, and remember it can only be consumed once.
What is the difference between map and filter in Python?
Map applies a function to every item and keeps the results, so the length stays the same. Filter keeps only the original items for which the function returns a truthy value.
Is map faster than a list comprehension?
It depends on the function. In our test a comprehension was faster when map used a lambda, while map was about 9 percent faster with the built-in str function.
What does filter with None do?
Passing None as the function keeps only truthy items, so it removes 0, empty strings, None and empty lists from an iterable.
Can map take more than one list?
Yes. Pass a function with several parameters and one iterable per parameter. Map pairs items by position and stops at the shortest iterable without any warning.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.