Pass Functions and Lambda Expressions
Core idea
A higher-order function takes a callable or returns one. Pass a function by name without parentheses when another function should call it later. lambda parameters: expression creates a function whose result is the expression value. A lambda body is a single expression, not a series of statements.
def apply_twice(fn, value): return fn(fn(value))def step(n): return n + 3print(apply_twice(step, 4))apply_twice calls the supplied function two times.
Sort by a field
rows = [("A", 8), ("B", 3)]print(sorted(rows, key=lambda row: row[1]))The key receives each row and returns its second field.
Use an existing callable
A named built-in is enough; no lambda wrapper is needed.
Common mistake
key=len() would call len immediately with no argument. Use key=len. Prefer def for multi-step logic or meaningful named reusable functions. Lambda captures names with the same late-binding rules as def.
Practice
Sort inventory tuples by quantity, then by label for ties, using a tuple-valued key. Repeat with a named function.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions as values
Check your understanding of lambda and higher-order functions.
What is printed?
def twice(fn, n): return fn(fn(n))print(twice(lambda n: n + 3, 3))What is printed?
print(sorted([("X", 5), ("Y", 1)], key=lambda row: row[1]))What is printed?
f = lambda n: n * 2print(f(4))Which expression passes a callable to sorted without executing it first?