Lambda, Map & Filter
Use anonymous functions and functional programming. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Data Translation MappingStudy 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.
pythonadd = 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.
pythonnums = ["1", "2", "3"] converted = list(map(int, nums)) print(converted)
Using filter
filter() keeps only items that return True.
pythonvalues = ["", "hi", "", "ok"] non_empty = list(filter(bool, values)) print(non_empty)
Sorting with a lambda key
A lambda is handy for custom sorting.
pythonpairs = [("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.
pythonnums = [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()orfilter()withlist()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()andfilter()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.
Data Translation Mapping
Filter parameters executing functional translations seamlessly.
Stream Trimming Filters
Reduce complex array strings effortlessly.
Compound Ordering
Apply sorted logic using lambda parameters processing complex mapping arrays.
Lexical Comparison Chains
Dynamically locate largest entries navigating arrays deeply using map objects conditionally.
Dictionary Transformation Mappings
Combine dict methods resolving sequences tracking complex values natively.