Lesson · Functional Programming Tools
Higher-Order Built-ins
55 min readHigher-Order Built-ins
Higher-order built-ins such as `map`, `filter`, and key-based `sorted` accept callables. Python often favors comprehensions for readability, but functional helpers remain valuable in pipelines and reusable APIs.
Learning goals
- Read a
maporfiltercall and say what the callable receives and what the iterator yields. - Pass an existing function such as
str.upperstraight tomapand explain why no lambda is needed. - Sort by a computed key and predict tie order from stability.
- Use
minormaxwithkey=and say which item is returned when keys tie. - Choose between a comprehension and a functional helper and justify the choice with readability.
Mental model
The built-ins in this lesson all accept a callable and decide for you when to call it: map once per item to produce a value, filter once per item as a test, and sorted or min/max once per item as a ranking score. The callable describes what happens to a single item; the built-in owns the iteration. Read every example that way and the missing loop stops being surprising.
Core idea
These built-ins invert control: instead of writing a loop that reaches into each item, you hand over a function and let the built-in run it at the right moment. map and filter stay lazy and composable, while sorted and min/max consume the sequence and return a result. The key function is the same idea applied to comparison, which is why one callable shape drives all of them.
map
map lazily applies a callable to items from one or more iterables and yields the results in order. It returns an iterator, so nothing runs until you consume it with list(), a loop, or another consumer; with several iterables it stops at the shortest one.
filter
filter lazily keeps the items for which a predicate returns a truthy value and yields them unchanged. Passing None as the predicate keeps the items that are already truthy, and the result is again an iterator.
sorted(key=...)
sorted(iterable, key=fn) builds a new list ordered by comparing fn(item) for each item instead of the items themselves. The key function runs once per item, the original sequence is unchanged, and reverse=True flips the order after sorting by key.
min/max(key=...)
min and max return the item with the smallest or largest fn(item), not the computed value itself. Ties keep the first item seen, which is why max(words, key=len) returns the first longest word.
Comprehensions vs functional helpers
A comprehension expresses the same transformation as map and filter in one expression and is usually the more readable choice when the work is a simple projection with a condition. map and filter still earn their place when the callable already exists (like str.upper) or when a lazy iterator must flow into the next stage without materializing a list.
Walkthrough
map(str.upper, words)yields'PEAR'through'APPLE'in order;str.upperis an unbound method used as the callable, which is why no lambda is needed.filter(lambda w: len(w) > 4, words)tests each word once and keeps'banana'and'apple'; the lambda returns abool, and filter keeps the items whose result is truthy.sorted(words, key=len)orders by length, and equal lengths keep their original order, so'banana'stays before'apple';max(words, key=len)returns the first item with the winning length,'banana'.- Predict before running: the four printed lines, and specifically which word
maxreturns when two words share the largest length.
Experiments to try
- Replace
str.upperwithstr.titleand then with a lambda that appends a suffix; check that all three callables fitmapunchanged. - Feed
maptwo lists, for examplemap(pow, [2, 3, 4], [5, 2, 3]), and state what the second iterable contributes. - Sort by
(len, word)and then by(len, word)withreverse=True; write down the tie rule each order produces. - Consume a
filterresult twice (two separatelist()calls) and explain the second result from the iterator rule.
Common mistakes
- Forgetting the laziness: printing a
mapobject shows an iterator, and a consumed one is empty on the second pass. - Passing a call instead of a callable to
map(map(str.upper(), words)); the parentheses callstr.upperwith no argument and raise beforemapever iterates. - Assuming
sorted(key=fn)returns the computed keys; the key only drives ordering, and the original items come back. - Writing
lambda w: w.upper()wherestr.upperalready does the job, which adds a wrapper without adding meaning.
Practice: Easy
- Run the worked example; then print
map(str.upper, words)withoutlist()and describe what the printout is. - Filter
wordson a predicate of your choice (for example, containing the lettera) and state the predicate plus the result. - Build
["Pear", "banana", "Fig", "apple"]and callsorted(words, key=str.lower); predict the order before running.
Practice: Medium
- Build a pipeline of
filterthenmapthat keeps five-letter words and capitalizes them; write the equivalent comprehension and pick the clearer form with one reason. - Compare
min(words, key=len)withmin(words, key=lambda w: (len(w), w)); explain what the tuple key changes when two words tie. - Sort a list of
(name, score)tuples by score descending and name ascending in one call; verify the order with two records that share a score.
Practice: Hard
- Implement a small records report: filter active records, map them to formatted strings, then sort by a computed key; define the types moving between stages and one boundary record with an empty name.
- Rewrite a loop that appends into three lists using
map/filterplus comprehensions; keep laziness where it helps and argue which version does less work before the first result. - Design a key-function comparison: same data, three keys (
len,str.lower, and a tuple key), predictions for tie behavior written first, then run and explain every mismatch with stability.
Lesson checklist
- I can explain why
mapandfilterdo nothing until their result is consumed. - I can pass an existing method to
mapwithout wrapping it in a lambda. - I can predict tie order for
sorted(..., key=...)from stability. - I can choose between a comprehension and a functional helper and defend the choice.
Remember
Higher-order built-ins accept a callable and control the iteration themselves: `map` transforms, `filter` selects, and `sorted` plus `min`/`max` rank. Laziness shapes how `map` and `filter` are read, stability shapes how ties are read, and the key function is the single lever shared by all of them. When the callable already exists these tools stay short; when the per-item logic grows, a comprehension usually reads better.
Interview angles
What is the main purpose of **map**?+
map lazily applies a callable to items from one or more iterables and yields the results in order. It returns an iterator, so nothing runs until you consume it, and with several iterables it stops at the shortest one.
What should you pay attention to when using **filter**?+
filter lazily keeps the items for which a predicate returns a truthy value and yields them unchanged. Passing None as the predicate keeps the items that are already truthy, and the result is again an iterator.
How does **sorted(key=...)** fit into this lesson?+
sorted(iterable, key=fn) builds a new list ordered by comparing fn(item) for each item instead of the items themselves. The key function runs once per item, the original sequence is unchanged, and reverse=True flips the order after sorting by key.
Why does `map(str.upper(), words)` fail before it can iterate?+
str.upper() is called immediately with no instance, so it raises TypeError before map runs. map needs the function object itself, so the correct form is map(str.upper, words).