← Python lessons

Python map() and filter() (and When to Use a Comprehension)

map() runs a function on every item in a list. filter() keeps only the items for which a function returns True. A list comprehension can do both.

Read Lambda functions first.

Change every item with map()

Pass map() a function and a list. It calls the function on each item.

answers = ["3", "14", "7"]
numbers = list(map(int, answers))
print(numbers)
print(sum(numbers))

map() hands back a map object, not a list. Wrap it in list() to get the values. Pass int without brackets: map() calls it for you.

Use map() with a lambda

When no built-in function does the job, write a lambda.

sides = [1, 2, 3, 4]
areas = list(map(lambda side: side * side, sides))
print(areas)

The lambda squares each side, so the list becomes [1, 4, 9, 16].

Keep some items with filter()

filter() calls the function on each item. It keeps the item when the function returns True and drops it when it returns False.

scores = [12, 4, 19, 7, 15]
passed = list(filter(lambda score: score >= 10, scores))
print(passed)

4 and 7 fail the test, so only [12, 19, 15] is left. The order stays the same.

When to use a comprehension instead

A list comprehension does the same jobs inside square brackets. Most Python programmers find it easier to read than map() or filter() with a lambda.

scores = [12, 4, 19, 7, 15]
print(list(map(lambda s: s * 2, scores)))
print([s * 2 for s in scores])

print(list(filter(lambda s: s >= 10, scores)))
print([s for s in scores if s >= 10])

print([s * 2 for s in scores if s >= 10])

Each pair prints the same list. The last line filters and changes in one step. Use a comprehension when you would need a lambda. Use map() when you already have a named function, as in map(int, answers).

Note: A map or filter object can be read only once. A second loop over it finds nothing. Save it with list() if you need the values again.

See also: Sorting, The accumulator pattern.

Your turn

Turn the answers into numbers with map(), then keep the even ones with filter(). Print them as a list.

answers = ["4", "7", "10", "3"]
# add three lines: map() the answers to int, filter() the even ones, print them as a list

Expected output

[4, 10]

Practise this in the free Python course, where every exercise checks your code instantly.