← All lessons

map and filter

Sign in · Sign up

Lesson 6.9

map applies a function to every item, filter keeps the ones that fit:

numbers = [1, 2, 3, 4, 5]

doubled = list(map(lambda x: x * 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))

The first argument is a function, the second is a list. map and filter return an iterator, not a list, so the result is wrapped in list(...).

The check sets the list of numbers numbers. Print, in order:

  1. each number divided by divisor — with map;
  2. only the numbers that divide by divisor with no remainder — with filter.
Hint

map applies a function to every item, filter keeps the ones where the function returned True.

Both return an iterator, so wrap them in list(...). In map — division by divisor, in filter — the check x % divisor == 0.