1.2.32 · D3Introduction to Programming (Python)

Worked examples — Lambda functions — anonymous, used with map - filter

2,154 words10 min readBack to topic

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 twistmap 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

Figure — Lambda functions — anonymous, used with map - filter

Worked examples


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 functionssum(map(...)) in Ex 9.

Decision map

yes

yes

yes

Have a list, want a result

Change every item?

Keep only some items?

Order items?

Use map with a lambda

Use filter with a predicate

Use sorted with key lambda

Wrap in list to see it