Transform Lazily with map and filter
Core idea
map(fn, iterable) produces the result of applying fn to each item. filter(predicate, iterable) yields the original items for which the predicate is truthy. Both return iterators in Python 3.13; they call the functions as items are requested. With multiple iterables map stops at the shortest input.
valid = filter(lambda n: n >= 0, [2, -1, 0, 3])print(list(map(lambda n: n * 10, valid)))Filtering retains zero because the predicate explicitly permits it.
Observe deferred calls
def scale(n): print("scale", n) return n * 2it = map(scale, [3, 5])print("ready")print(next(it))Only the requested first item has been transformed.
Combine parallel inputs
print(list(map(lambda a, b: a + b, [2, 4, 6], [10, 20])))The unmatched last item of the longer list produces no result.
Common mistake
filter(None, items) removes all falsey items, including zero and empty strings, not just None. A consumed map or filter iterator is not reusable.
Practice
Strip whitespace from each string label using map, then remove the empty results using filter. Return a list and test whitespace-only labels, duplicates and empty input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Map and filter
Check your understanding of map and filter.
What is printed?
print(list(map(lambda x: x * 2, filter(lambda x: x >= 0, [-1, 0, 3]))))What is printed?
it = map(lambda n: n + 1, [2])print(list(it), list(it))What is printed on Python 3.13?
print(list(map(lambda a, b: a + b, [2, 3], [5])))What does filter(None, items) retain?