Worked examples — Lambda functions — anonymous, used with map - filter
The scenario matrix
Think of a lambda-with-a-tool problem as having a few independent "dials". Each dial can be in a few positions. The matrix below lists every position we must cover so you never meet a case we didn't show.
| Cell | Case class | What could bite you |
|---|---|---|
| A | map transforms a normal list |
forgetting list(...) → see <map object> |
| B | filter selects with a predicate |
x % 2 == 0 vs x % 2 == 1 sign of remainder |
| C | empty / degenerate iterable [] |
result is [], not an error |
| D | laziness — iterator exhausts after one pass | second list() gives [] |
| E | nesting map(f, filter(g, it)) |
inside-out evaluation order |
| F | multi-argument lambda + sorted(key=...) |
one comparable value per item |
| G | truthiness filter(lambda x: x, ...) |
drops 0, '', None, [], False |
| H | ternary inside lambda (the only "logic" allowed) | if/else as an expression, not a statement |
| I | real-world word problem | choosing map vs filter |
| J | exam twist — map over two iterables |
map(f, a, b) stops at the shorter |
We now work 10 examples, each tagged with the cell(s) it covers. Together they fill the whole table.
The figure we keep referring to

Worked examples
Statement. Square only the odd numbers of [1, 2, 3, 4, 5, 6].
list(map(lambda x: x * x,
filter(lambda x: x % 2 == 1, [1,2,3,4,5,6])))Forecast: what's left after both stages?
- Read inside-out: the innermost call runs first —
filter(lambda x: x % 2 == 1, ...). Why this step? Function calls evaluate their arguments before the outer call runs. - Filter keeps odds:
[1, 3, 5]. Why this step? Odd numbers leave remainder1when divided by2. map(lambda x: x*x, ...)squares each survivor:1→1, 3→9, 5→25. Why this step?maptransforms the already-thinned stream — cheaper than squaring all six.
Result: [1, 9, 25]
Verify: 3 odds in ⇒ 3 squares out; every output is an odd number squared. ✓
sorted's key (Cell F)
Statement. Sort students by their score (descending), then show names.
people = [("Asha", 82), ("Ravi", 91), ("Meena", 77)]
ranked = sorted(people, key=lambda p: p[1], reverse=True)
names = list(map(lambda p: p[0], ranked))Forecast: who is first?
key=lambda p: p[1]handssortedone comparable value per item — the score. Why this step?sortedcompares items; a tuple would compare by name first, which we don't want.reverse=Trueflips ascending → descending, so highest score leads. Why this step? We want a ranking, top down.map(lambda p: p[0], ranked)pulls the name (index0) out of each ranked tuple.
Result: ranked = [("Ravi",91),("Asha",82),("Meena",77)], names = ["Ravi","Asha","Meena"].
Verify: scores 91 ≥ 82 ≥ 77 are non-increasing. ✓ See sorted and key functions.
Statement. list(filter(lambda x: x, [0, 1, '', 'hi', None, [], [0], False, 5])) = ?
Forecast: which of these count as "empty/false"?
filter(lambda x: x, ...)keepsxwhenbool(x)isTrue. Why this step? The lambda just returns the item itself;filterthen asksbool(...).- Falsy values dropped:
0,'',None,[],False. Why this step? Python treats "empty or zero" containers/numbers asFalse. - Truthy survivors:
1,'hi',[0](a non-empty list is truthy even if it holds a0),5.
Result: [1, 'hi', [0], 5]
Verify: every survivor is non-empty / non-zero; every dropped value is a canonical falsy. ✓
Statement. Label each number even/odd:
list(map(lambda x: 'even' if x % 2 == 0 else 'odd', [1, 2, 3, 4]))Forecast: guess the four labels.
a if condition else bis an expression (it produces a value), so it's legal in a lambda. Why this step? Lambdas forbid statements (if x:on its own line) but allow this one-line conditional.- Evaluate per item:
1→odd, 2→even, 3→odd, 4→even. Why this step?mapruns the tiny classifier once per element.
Result: ['odd', 'even', 'odd', 'even']
Verify: even indices of value (2, 4) map to 'even'. ✓
elif too"
A ternary has exactly A if C else B. Need three branches? Nest — A if C1 else (B if C2 else C) — or better, use a named def. Readability wins.
Statement. A shop's cart prices are [199, 0, 499, 0, 89] (the 0s are removed items). Compute the total after adding 18% GST, ignoring removed items.
Forecast: map or filter first — and why?
- Filter out removed items (the
0s):filter(lambda p: p > 0, prices)→[199, 499, 89]. Why this step? We select real items before doing any maths — filter is the selector. - Map each surviving price to its GST-inclusive value:
lambda p: p * 1.18. Why this step? Every real item is transformed the same way — that's map's job. - Sum the results with built-in
sum(...). Why this step?sumfolds the mapped iterator into one number (a higher-order reduction).
prices = [199, 0, 499, 0, 89]
total = sum(map(lambda p: p * 1.18,
filter(lambda p: p > 0, prices)))Result: 787 * 1.18 = 928.66
Verify: kept sum 199 + 499 + 89 = 787; 787 * 1.18 = 928.66. Units: rupees × (dimensionless factor) = rupees. ✓
map over TWO iterables (Cell J)
Statement. list(map(lambda a, b: a + b, [1, 2, 3, 4], [10, 20, 30])) = ?
Forecast: four results or three?
- When you pass two iterables,
mapcalls the lambda with one element from each, in lock-step. Why this step? The lambda has two parametersa, b;mapfeeds them in parallel. - Pairs:
(1,10), (2,20), (3,30)→ sums11, 22, 33. Why this step?mapstops at the shortest iterable, so the leftover4is never used.
Result: [11, 22, 33] (length 3, not 4).
Verify: min(len([1,2,3,4]), len([10,20,30])) == 3 matches the output length. ✓
Matrix coverage check
Recall Did we fill every cell? (reveal)
A→Ex1 · B→Ex2 · C→Ex3 · D→Ex4 · E→Ex5 · F→Ex6 · G→Ex7 · H→Ex8 · I→Ex9 · J→Ex10. Every row is worked. ✓
Recall Rapid self-test
list(map(lambda x: x*3, [1,2,3,4])) ::: [3, 6, 9, 12]
list(filter(lambda x: x % 2 == 0, [10,15,20,25])) ::: [10, 20]
list(filter(lambda x: x, [0,1,'', 'hi', None, [], [0], False, 5])) ::: [1, 'hi', [0], 5]
list(map(lambda a,b: a+b, [1,2,3,4],[10,20,30])) ::: [11, 22, 33]
Second list() on an exhausted map object gives? ::: []
Connections
- Functions and def — every lambda here has an equivalent named
def. - First-class functions — why we can hand functions to
map/filter/sorted. - List comprehensions — Ex 5 is
[x*x for x in nums if x % 2 == 1]. - Iterators and lazy evaluation — the engine behind Ex 3, 4, 10.
- sorted and key functions — the tool in Ex 6.
- Higher-order functions —
sum(map(...))in Ex 9.