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.
- Apply an existing function to every item with
list(map(func, items)) - Keep items with
list(filter(func, items)), includingfilter(None, …)to drop empty values - Know that a
maporfilterobject can be walked only once, and has no positions
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.
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.
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))
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.
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,minandmax, with a key for records and a default for empty inputs.