Python map() & filter()
In this page:
The map() Function
map(function, iterable) applies the given function to every element of the iterable and returns a lazy iterator of the results, not a list -- wrap it in list() if you need the actual values materialized rather than just an iterator you can loop over once.
Example: The map() Function
nums = [1, 2, 3]
result = map(str, nums)
print(list(result))
map() with Lambda
Pairing map() with a lambda lets you apply a quick, throwaway transformation inline without defining a separate named function first, which is convenient for simple one-line operations like squaring every number in a list.
Example: map() with Lambda
nums = [1, 2, 3]
squares = map(lambda x: x * x, nums)
print(list(squares))
The filter() Function
filter(function, iterable) keeps only the elements for which the given function returns a truthy value, discarding the rest -- like map(), it also returns a lazy iterator rather than a list, so you again wrap it in list() when you need concrete results.
Example: The filter() Function
def is_even(n):
return n % 2 == 0
nums = [1, 2, 3, 4, 5, 6]
print(list(filter(is_even, nums)))
filter() with Lambda
A lambda inside filter() is the common pattern for quick, inline conditions, like filter(lambda x: x % 2 == 0, numbers) to keep only even numbers, without needing a separately defined is_even function just for this one use.
Example: filter() with Lambda
nums = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, nums)
print(list(evens))
Combining map() and filter()
Nesting map() around filter() lets you filter a sequence down to the elements you care about and then transform only those survivors, in a single expression -- though for anything beyond a simple case, a list comprehension usually reads more clearly than stacking map() and filter() together.
Example: Combining map() and filter()
nums = [1, 2, 3, 4, 5, 6]
result = map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums))
print(list(result))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects