Lambda, map, filter
- Define anonymous functions with
lambda - Transform sequences with
map()and comprehensions - Filter sequences with
filter()and comprehensions - Know when to prefer a named function over a lambda
PEP 8 and most style guides (Google, Black-adjacent) prefer comprehensions over map/filter, but lambdas remain load-bearing in pandas .apply, sorted(key=...), and functools.reduce. Knowing when to reach for operator.itemgetter over lambda is a real perf win.
- Assigning a lambda to a name —
f = lambda x: x+1fails linting; usedeffor anything named. - Late binding in loop-defined lambdas —
[lambda: i for i in range(3)]all return 2; pin withlambda i=i: i. - Reaching for
map(lambda x: x.name, items)whenoperator.attrgetter('name')is faster and clearer.
lambda args: expr — an unnamed function for short one-liners. Don't write multi-line lambdas; define a real function instead.
The Pythonic preference
[f(x) for x in seq] is usually clearer than list(map(f, seq)). But map/filter shine when passing functions around or chaining.
Where you'll really use lambdas
sorted(items, key=lambda x: x.name) — providing a key function inline.
Try it
- Sort
[("Ada", 30), ("Bob", 25)]by age. - Use
filterto keep only positive numbers from[-2, -1, 0, 1, 2].
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given
nums = [1, 2, 3, 4, 5], usemapwith a lambda to build a list of each number cubed, then print it. Expected:[1, 8, 27, 64, 125]. - Exercise 2
From
values = [-3, -1, 0, 2, 5, -8, 4], usefilterwith a lambda to keep only positive numbers (>0), then print the list. Expected:[2, 5, 4]. - Exercise 3
Given
people = [("Ada", 30), ("Bob", 25), ("Cara", 40)], sort by age ascending usingsortedwith a lambda key, then print the sorted list.