Lesson 8 of 16 · Functions in Depth
Map, Filter and Sorted
Learn Python's map, filter and sorted functions: transform and filter data, sort with keys, and see how they compare with list comprehensions.
- 7 min read
- Intermediate
- Reviewed
- How map() applies a function to every item
- How filter() keeps the items that pass a test
- How sorted() differs from list.sort()
- When to choose these functions or a comprehension
Three tools for working with collections
Python has three built-in functions that take a function and a collection:
| Function | What it does |
|---|---|
map(function, items) | Applies the function to every item |
filter(function, items) | Keeps the items for which the function returns True |
sorted(items, key=function) | Returns a new sorted list |
You will often see them with the lambdas from the last lesson.
map: transform every item
prices = [10, 25, 40] with_tax = map(lambda price: price * 1.2, prices) print(with_tax) print(list(with_tax))
The first print shows something like <map object at 0x...>. map() does not build a list straight away. It returns a map object that produces each result only when asked. Wrapping it in list() asks for all of them.
You can pass any function, not only a lambda. Built-in functions work well:
words = [" data ", "Model", " AI "] numbers_as_text = ["3", "14", "15"] print(list(map(str.strip, words))) print(list(map(int, numbers_as_text))) print(sum(map(int, numbers_as_text)))
map(int, ...) is a classic way to convert a list of text numbers into real numbers.
filter: keep some items
filter() keeps the items for which the function returns True.
scores = [92, 45, 78, 61, 88, 39] passed = filter(lambda score: score >= 60, scores) print(list(passed))
Like map(), filter() returns an object that you turn into a list with list().
A neat trick: filter(None, items) removes every "empty" value, such as 0, "", None and empty lists.
answers = ["yes", "", "no", None, "maybe", ""] print(list(filter(None, answers)))
sorted and list.sort
There are two ways to sort. They look similar but behave differently.
numbers = [5, 2, 9, 1] new_list = sorted(numbers) print(new_list) print(numbers) numbers.sort() print(numbers)
sorted(items) | items.sort() | |
|---|---|---|
| Works on | any collection, including tuples, sets and strings | lists only |
| Original | unchanged | changed in place |
| Returns | a new list | None |
Both accept key= and reverse=True.
cities = ["Lagos", "Tokyo", "Lima", "Mumbai"]
print(sorted(cities, key=len))
print(sorted(cities, reverse=True))
print(sorted("python"))Comprehension or map and filter?
The same work can usually be done with a comprehension.
scores = [92, 45, 78, 61] # With map and filter curved = list(map(lambda s: s + 5, filter(lambda s: s >= 60, scores))) # With a comprehension curved_too = [s + 5 for s in scores if s >= 60] print(curved) print(curved_too)
Both give the same answer, but the comprehension reads more naturally. Most Python programmers prefer comprehensions, and use map() mainly when they already have a named function, as in map(int, values) or map(str.strip, lines).
Common mistakes
Clean up a list of text numbers with filter(), map() and sorted().
raw = ["42", "7", "", "19", "3", ""] # 1. Use filter(None, ...) to remove the empty strings # 2. Use map(int, ...) to turn the rest into numbers # 3. Print them sorted from largest to smallest # Output must be exactly: # [42, 19, 7, 3]
What is printed by: n = [3, 1, 2]; print(n.sort())
Summary
map(function, items)applies a function to every item.filter(function, items)keeps the items that pass a test.- Both return lazy objects: wrap them in
list()to see the values. sorted()returns a new list, whilelist.sort()changes the list and returnsNone.- A comprehension is often clearer than
mapandfilterwith lambdas.
You have finished the module on functions. Next, you will work with text and data files.
Finished reading? Tick it off to track your progress.