IntermediateLesson firstCategory 12 of 20

Lambda, Map & Filter

Use anonymous functions and functional programming. Read the lesson first, then move through the exercises in order.

7 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Data Translation Mapping

Study Material

Read the full lesson

Lambda functions

A lambda is a small anonymous function for short tasks. If the logic is long, use a normal def.

python
add = lambda a, b: a + b print(add(2, 3))

Using map

map() applies a function to every item. It returns an iterator, so use list() if you want to see the results.

python
nums = ["1", "2", "3"] converted = list(map(int, nums)) print(converted)

Using filter

filter() keeps only items that return True.

python
values = ["", "hi", "", "ok"] non_empty = list(filter(bool, values)) print(non_empty)

Sorting with a lambda key

A lambda is handy for custom sorting.

python
pairs = [("a", 3), ("b", 1), ("c", 2)] print(sorted(pairs, key=lambda p: p[1]))

When a list comprehension is clearer

Many map() and filter() cases are easier to read as comprehensions.

python
nums = [1, 2, 3, 4] result = [n * 2 for n in nums if n % 2 == 0] print(result)

Common mistakes to avoid

  • Overusing lambdas for long logic.
  • Forgetting to wrap map() or filter() with list() when you need a list.
  • Using lambdas when a named function would be clearer.

What you should understand after this lesson

  • What a lambda is and when to use it.
  • How map() and filter() work.
  • When a list comprehension is a better choice.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.