runtime
69 / 250
lesson 69 Built-ins & Sorting · intermediate

map and filter, or a comprehension?

`map` applies a function to every item and `filter` keeps the items a function accepts. They shine when the function already exists; otherwise a comprehension usually reads better.

You'll be able to
  • Apply an existing function to every item with list(map(func, items))
  • Keep items with list(filter(func, items)), including filter(None, …) to drop empty values
  • Know that a map or filter object can be walked only once, and has no positions
The idea

Functions are values: you passed one to sorted as a key. map(func, items) calls func on every item; filter(func, items) keeps the items for which func returns something true. Both hand back a lazy iterator that produces values only when asked, so wrap it in list(...) to get a list.

They read best when the function already exists: a built-in like float, a method like str.upper, or a function you wrote and named.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Convert a column, tidy some codes
cells = ["7.49", " 31", "171.99 "]
prices = list(map(float, cells))
print(prices)
codes = list(map(str.upper, ["las", "iah", "mci"]))
print(codes)

filter needs a function that answers yes or no. A named function documents the rule in one place, and the filter line reads like a sentence. One catch: the iterator is used up as it is walked. A second list(...) of the same object is empty.

example-2.py · Valid airport codes, walked twice
def is_airport_code(code):
    return len(code) == 3 and code.isalpha() and code.isupper()

entries = ["LAS", "iah", "MCI", "DFW1", "BOS"]
valid = filter(is_airport_code, entries)
print(list(valid))
print(list(valid))
example-3.py · A map object has no positions
prices = map(float, ["7.49", "31"])
print(prices[0])

filter(None, items) keeps the items that are truthy themselves, which is a quick way to drop empty texts and zeros.

Which to choose: if you would have to write a new one-off function just to call map or filter, a comprehension says it more directly: [p * 1.2 for p in prices] beats defining add_tax for one use. If the function already exists, map(float, cells) is short and clear. Mistakes to avoid: printing a map object (you see <map object at …>, not values), indexing it, and walking it twice.

Review
  • list(map(func, items)) applies an existing function to every item; list(filter(func, items)) keeps the accepted ones.
  • They return one-pass iterators: no positions, and empty the second time.
  • Write a comprehension when you would otherwise invent a one-off function just to pass it.
  • Next: sum, min and max, with a key for records and a default for empty inputs.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

map and filter, or a comprehension? — Built-ins & Sorting · Runtime