Lesson 22
map, filter & lambda
A lambda is a tiny unnamed function: lambda n: n * 2. It is limited to one expression.
map(function, items) applies a function to every item. filter(function, items) keeps items where the function returns true.
Both return lazy iterators, so wrap them in list() to see the results. A comprehension is often clearer for simple cases.
nums = [1, 2, 3, 4] doubled = list(map(lambda n: n * 2, nums)) print(doubled)
Check your understanding
What does filter keep?
CHALLENGE
From [1, 2, 3, 4, 5, 6], use filter with a lambda to keep the even numbers. Print the list.
Practice →