Code

map, filter & reduce

Three classic tools apply a function across a collection:

from functools import reduce

nums = [4, -1, 3, -7]

list(map(abs, nums))                      # [4, 1, 3, 7]
list(filter(lambda n: n > 0, nums))       # [4, 3]
reduce(lambda a, b: a + b, nums, 0)       # -1
  • map(func, items) calls func on every item.
  • filter(func, items) keeps items where func returns something truthy.
  • reduce(func, items, start) folds everything into one value: ((0 + 4) + -1) + .... The start value is used for empty inputs.

map and filter are lazy: they hand back an iterator that produces values on demand, so wrap them in list() to see them all.

Often a comprehension reads better ([n for n in nums if n > 0]), but map is lovely when you already have a function: map(str.strip, lines).

These tools work best with pure functions: functions whose result depends only on their arguments and that don't change anything outside themselves. Pure functions are easy to test, reuse and combine.

Assignment

Use the tool named in each step:

  1. clean_names(names): with map, strip spaces and title-case each name (" ada lovelace " becomes "Ada Lovelace"). Return a list.
  2. positives(nums): with filter, keep numbers above 0. Return a list.
  3. product(nums): with reduce, multiply all numbers together. An empty list gives 1.