Skip to content

Lesson 14 of 52Functions

Higher-Order Functions

Treat functions as values, pass them to map, filter and sorted, write lambdas, and use reduce and partial.

19 min read0/6 questions

In Python a function is a value, just like a number or a list. You can store it, pass it to another function, or return it. That one idea powers sorting by any field (sorted(users, key=...)), event handlers, retry wrappers, and the decorators you will meet later. Being comfortable with key= functions alone will make you noticeably faster in interviews.

Functions are values

When you write def shout(text): ..., Python creates a function object and ties the name shout to it, exactly like x = 5 ties x to an int. Without parentheses, shout is the function itself; with parentheses, shout(...) calls it.

Python
def shout(text): return text.upper() + "!" yell = shout # a second name for the same functionprint(yell("hi"))print(type(shout)) actions = {"loud": shout, "quiet": str.lower}print(actions["loud"]("hey"), actions["quiet"]("HEY"))
Output
Press Run (⌘ Enter) to see what happens.

That last pattern, a dict of functions, is called a dispatch table. It replaces long if/elif chains that pick an action by name.

A higher-order function is one that takes a function as an argument, returns a function, or both. You already wrote one: make_multiplier in Scope and Closures returned a function.

Python
def apply_twice(fn, value): return fn(fn(value)) def add_three(n): return n + 3 print(apply_twice(add_three, 10))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
You want run_later to call save later. Which call is right?
Need a nudge? A hint rules out a wrong answer.

lambda: small anonymous functions

A lambda is a function written as a single expression, with no name and no return keyword: lambda params: expression. It is handy when you need a tiny function for one call.

Python
square = lambda n: n * n # works, but def is clearer for named functionsprint(square(7)) pairs = [(1, "b"), (3, "a"), (2, "c")]print(sorted(pairs, key=lambda p: p[1]))
Output
Press Run (⌘ Enter) to see what happens.

Lambdas can only hold one expression: no statements, no assignments, no loops. PEP 8 also advises against assigning a lambda to a name (square = lambda ...); use def for anything you want to name and reuse. Lambdas shine as throwaway arguments.

sorted, min and max with key=

sorted, list.sort, min and max all accept a key function. Python calls it once per item, then compares the results instead of the items.

sorted(words, key=len)
banana
0
fig
1
cherry
2
kiwi
3

Start with four words. By default, sorted would compare them alphabetically.

1/4
Python
users = [ {"name": "Sam", "age": 31}, {"name": "ada", "age": 25}, {"name": "Priya", "age": 42},] print([u["name"] for u in sorted(users, key=lambda u: u["age"])])print([u["name"] for u in sorted(users, key=lambda u: u["name"].lower())])print(max(users, key=lambda u: u["age"])["name"])print(sorted(["b", "A", "c"], key=str.lower, reverse=True))
Output
Press Run (⌘ Enter) to see what happens.

To sort by two things, return a tuple from the key: key=lambda u: (u["age"], u["name"]) sorts by age, then by name for equal ages. Tuples compare item by item.

Predict the outputPython

What does this print?

words = ["pear", "Fig", "apple"]
print(sorted(words))
print(sorted(words, key=str.lower))
Need a nudge? Hints walk you through it.

Sort stability and multi-key sorts

Real sorts rarely use one field. "Team A to Z, then salary highest first, then name" is a normal product requirement, and there are two clean ways to write it.

One pass with a tuple key. Tuples compare item by item, so the tuple lists the keys from most to least important. For a numeric key you want descending, negate it.

Several passes, least important key first. Because Python's sort is stable, items that tie on the current key keep the order from the previous pass. So you sort by the tie-breaker first and by the main key last.

Python
from operator import itemgetter staff = [ ("Ada", "eng", 120), ("Sam", "ops", 95), ("Lee", "eng", 120), ("Priya", "ops", 110), ("Bo", "eng", 101),] # team A to Z, then salary high to low, then name A to Zprint(sorted(staff, key=lambda s: (s[1], -s[2], s[0]))) # same result with stable passes: least important key firstby_name = sorted(staff, key=itemgetter(0))by_salary = sorted(by_name, key=itemgetter(2), reverse=True)by_team = sorted(by_salary, key=itemgetter(1))print(by_team)
Output
Press Run (⌘ Enter) to see what happens.
Two stable passes: team Z to A, then name A to Z
Ada/eng
0
Sam/ops
1
Lee/eng
2
Bo/ops
3

Four rows. We want ops before eng, and names A to Z within a team.

1/3

The multi-pass version earns its place when one key is a string you want descending. You cannot write -name, but you can sort by name first and then by the other key with reverse=True. reverse=True keeps the sort stable: ties still come out in their original order, rather than being flipped.

Python
rows = [("Ada", "eng"), ("Sam", "ops"), ("Lee", "eng"), ("Bo", "ops")] # team Z to A, then name A to Z: you cannot negate a stringrows.sort(key=lambda r: r[0]) # secondary firstrows.sort(key=lambda r: r[1], reverse=True) # then primaryprint(rows)
Output
Press Run (⌘ Enter) to see what happens.

A few things seniors know about sorting:

  • Stability is guaranteed by the language, not an accident of the implementation. You can rely on it in production code.
  • key runs once per item, and the results are cached for the sort. An expensive key, like parsing a date string, is computed n times, not n log n times.
  • list.sort() sorts in place and returns None. users = users.sort() is a classic bug that leaves you with None.
  • Old-style compare functions (return negative, zero or positive) still exist in other languages and old code. functools.cmp_to_key adapts one to a key, but a tuple key is almost always clearer.
  • operator.itemgetter and attrgetter replace simple lambdas like lambda r: r[1] and accept several fields at once: itemgetter(1, 0) returns a tuple. They are a little faster and can be pickled. functools, itertools and operator covers them in depth.
Predict the outputPython

What does this print?

scores = [("lee", 7), ("ada", 9), ("sam", 7), ("bo", 9)]
print(sorted(scores, key=lambda s: (-s[1], s[0])))
Need a nudge? Hints walk you through it.

map and filter

map(fn, iterable) applies fn to every item. filter(fn, iterable) keeps the items where fn returns something truthy. Both return lazy iterators, so wrap them in list() to see the results.

Python
prices = ["4.50", "10", "3.25"]print(list(map(float, prices))) nums = [5, -2, 0, 8, -1]print(list(filter(lambda n: n > 0, nums))) # the same with comprehensions, usually preferred in Pythonprint([float(p) for p in prices])print([n for n in nums if n > 0])
Output
Press Run (⌘ Enter) to see what happens.

In modern Python, comprehensions are usually clearer than map and filter with a lambda. map reads well when you already have a named function, like map(str.strip, lines) or map(int, parts).

Match the pairs0/4 matched

Match each call to its result.

Choose an item, then its match on the other side.

reduce: folding a list into one value

functools.reduce(fn, items, start) combines items pairwise: it calls fn(start, first), then fn(result, second), and so on, until one value is left.

Python
from functools import reduce nums = [1, 2, 3, 4]product = reduce(lambda acc, n: acc * n, nums, 1)print(product) # for common cases there is a clearer built-inimport mathprint(math.prod(nums), sum(nums), max(nums))
Output
Press Run (⌘ Enter) to see what happens.

reduce is powerful but often less readable than a loop or a built-in like sum, max, any or math.prod. Reach for it when no built-in fits.

Put it in order4 steps

Order the steps of reduce(lambda acc, n: acc + n, [2, 3, 4], 10).

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

partial: pre-filling arguments

functools.partial(fn, *args, **kwargs) makes a new function with some arguments already filled in. It is a tidy alternative to writing a small wrapper or lambda.

Python
from functools import partial def power(base, exponent): return base ** exponent square = partial(power, exponent=2)cube = partial(power, exponent=3)print(square(5), cube(2)) parse_binary = partial(int, base=2)print(parse_binary("1011"))
Output
Press Run (⌘ Enter) to see what happens.

partial also avoids the late-binding problem from the last lesson, because it stores the argument values at the moment you create it.

Strategy pattern with a dict of functions

The dispatch table from the start of this lesson grows into a real design pattern. When behaviour varies by a name that arrives as data (a pricing plan, a file format, a payment provider, a command typed by a user), store one function per option and pick it at run time. In class-heavy languages this is the Strategy pattern, with an interface and one class per strategy. In Python, a function already is a one-method object, so a dict of functions is usually enough.

Python
from collections.abc import Callable type PriceRule = Callable[[int], int] # cents in, cents out PRICING: dict[str, PriceRule] = {} def rule(name: str) -> Callable[[PriceRule], PriceRule]: def register(fn: PriceRule) -> PriceRule: PRICING[name] = fn return fn return register @rule("standard")def standard(cents: int) -> int: return cents @rule("member")def member(cents: int) -> int: return cents * 90 // 100 def bulk(threshold: int, pct_off: int) -> PriceRule: def apply(cents: int) -> int: return cents * (100 - pct_off) // 100 if cents >= threshold else cents return apply PRICING["wholesale"] = bulk(threshold=10_000, pct_off=25) def checkout(cents: int, plan: str) -> int: try: price = PRICING[plan] except KeyError: raise ValueError(f"unknown plan {plan!r}; choose from {sorted(PRICING)}") from None return price(cents) print(checkout(2_000, "member"))print(checkout(12_000, "wholesale"), checkout(5_000, "wholesale"))try: checkout(2_000, "gold")except ValueError as err: print("ValueError:", err)
Output
Press Run (⌘ Enter) to see what happens.

Three higher-order ideas work together here. rule("member") is a decorator factory that registers a function in the table (you will write these yourself in Decorators). bulk(...) is a function factory: it returns a configured strategy, so one piece of code covers every "N percent off above X" deal. And checkout takes the strategy from the table and calls it, without knowing which one it got.

Why teams like this shape:

  • Adding an option is adding an entry. No if/elif chain to edit, so new plans do not touch checkout and are less likely to break existing ones.
  • Unknown names fail loudly with a list of valid choices, instead of falling through to an else that does something surprising.
  • Each strategy is tested on its own, as a plain function with plain inputs.

When does it stop being enough? When each option needs several related operations (price, describe, validate), a dict of single functions turns into several parallel dicts that drift apart. That is the point to switch to small classes sharing a Protocol, covered in Generics and Protocols in Depth. And if the set of names is fixed and known in code, rather than arriving as data, consider an Enum key so typos are impossible (see Enums).

Callbacks and typing Callable

A callback is a function you hand to other code so it can call you back at the right moment: "when a retry happens", "when the upload finishes", "for each row". The receiving code decides when; you decide what. Event handlers, key= functions and test hooks are all callbacks.

Python
from collections.abc import Callable def retry[T]( action: Callable[[], T], attempts: int = 3, on_retry: Callable[[int, Exception], None] | None = None,) -> T: for n in range(1, attempts + 1): try: return action() except ConnectionError as err: if n == attempts: raise if on_retry is not None: on_retry(n, err) raise AssertionError("unreachable") calls = 0def flaky() -> str: global calls calls += 1 if calls < 3: raise ConnectionError(f"timeout #{calls}") return "ok" def log_retry(attempt: int, err: Exception) -> None: print(f"attempt {attempt} failed: {err}") print(retry(flaky, on_retry=log_retry))
Output
Press Run (⌘ Enter) to see what happens.

Reading the types:

  • Callable[[int, Exception], None] is "a function taking an int and an exception, returning nothing". The first part is a list of positional parameter types; the second is the return type.
  • Callable[[], T] takes no arguments and returns some type T. The [T] after retry (Python 3.12 syntax) ties it to the return type of retry, so retry(flaky) is known to return str.
  • Callable[..., Any] accepts any arguments and returns anything. It is an escape hatch that turns off checking for every call through it. Use it only when you really cannot say more.
  • Import Callable from collections.abc. The typing.Callable alias still works but is deprecated in the docs.

Callable cannot describe keyword arguments, defaults or overloads. When a callback needs those, write a Protocol with a __call__ method, which you will see in Generics and Protocols in Depth. For wrappers that must keep the exact signature of the function they wrap, the tool is ParamSpec (Typing Patterns for Real Code).

Callback design habits worth copying: make callbacks optional with None as the default, document when they are called and with what, and decide what happens if a callback raises. In retry above, an exception inside on_retry escapes and stops the retries, which is usually right for a bug in your logger, but a UI event system might catch and log it instead so one bad handler cannot break the others.

Quick check
Which annotation fits a callback that receives a filename and a byte count and returns nothing?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Sort by length

Write sort_by_length(words) that returns a new list sorted from shortest to longest. Words of the same length go in alphabetical order.

sort_by_length(["banana", "fig", "apple", "kiwi"])  →  ["fig", "kiwi", "apple", "banana"]
sort_by_length(["bb", "aa", "c"])                  →  ["c", "aa", "bb"]
Python
def sort_by_length(words: list[str]) -> list[str]: # sorted() takes a key function pass
ChallengeMedium

Compose two functions

Write compose(f, g) that returns a new function. Calling it with x returns f(g(x)): run g first, then f on the result.

def add_one(x): return x + 1
def double(x): return x * 2
 
compose(add_one, double)(5)  # 11  (double first, then add one)
compose(double, add_one)(5)  # 12
Python
def compose(f, g): # Return a function, do not call f or g yet. pass
Key terms
first-class function
Functions are values: they can be stored, passed as arguments and returned.
higher-order function
A function that takes a function as an argument or returns one.
lambda
A one-expression anonymous function: lambda x: x * 2.
key function
Passed as key= to sorted, min, max; computes the value to compare for each item.
stable sort
Items with equal keys keep their original relative order.
functools.partial
Creates a new function with some arguments pre-filled.
strategy pattern
Choosing behaviour at run time by picking one of several interchangeable functions, often from a dict.
callback
A function you pass to other code so it can call you at the right moment.
Callable
The type of a function: Callable[[int, str], bool] lists parameter types, then the return type.