Python map() and filter()
map() changes every item in a list. filter() keeps only the items where the test is True.
Change every item
map() applies str.upper to each name. list() shows the changed names.
names = ["ada", "bob", "cy"]
print(list(map(str.upper, names)))Keep the passing items
The test keeps scores of 90 or more. The rest drop out.
scores = [88, 95, 71, 92]
print(list(filter(lambda n: n >= 90, scores)))A map object is not a list
list() turns the map object into a list you can print. Without it, you see the object, not the items.
nums = [1, 2, 3]
doubled = list(map(lambda n: n * 2, nums))
print(doubled)
print(len(doubled))Example
prices = [5, 10, 15, 20, 25]
with_tax = list(map(lambda p: p * 1.2, prices))
pricey = list(filter(lambda p: p >= 10, with_tax))
print("With tax:", with_tax)
print("Pricey:", pricey)
print("Count:", len(pricey))Key points
- map(): a built-in that changes every item with one function
- Use map(function, items) to apply the function to each item
- filter(): a built-in that keeps only the items that pass a test
- Use filter(test, items) to keep the items where the test is True
- map() gives back a map object, not a list. Wrap it in list() to see the items.
- filter() gives back a filter object, not a list. Wrap it in list() too.
- Both work with a lambda when the job is one short line
- Use map() and filter() to replace short loops that only change or keep items.
In this example, the list holds five prices. map() multiplies each price by 1.2 to add tax. filter() then keeps only the taxed prices of 10 or more. The first printout shows all five taxed prices. The second shows the four that pass the test. The count of 4 proves the filter kept exactly four items.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does list(map(str.upper, ["a", "b"])) give back?