1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
Python map and filter explained with examples and list comprehension timings

Key takeaways

  • 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), or filter(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. Write map(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, ...) removes 0 and 0.0 as 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 print does 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →