Paul's Python CoursePPC

map and filter

Not met yet

map(f, items) gives f(item) for each item. filter(f, items) keeps the items where f(item) is true. Both are lazy: they hand back an object that works each value out as you loop over it, so wrap them in list() to get them all at once. A list comprehension does the same jobs; use whichever the next person will read more easily.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks map() and filter() hand back a list, so len() and indexing work on the result straight away.
  • Thinks filter() throws away the items its function says yes to, rather than keeping them.

Where it comes up