Python: Higher-Order Functions and Lambda
Last updated: 2026-09-22
In Python, functions are also "values" — they can be assigned to variables, passed to other functions, just like numbers and strings. This enables very concise and elegant code. Higher-order functions are functions that take other functions as arguments or return functions. This lesson will open a new world for you.
1. Functions Are First-Class Citizens
In Python, functions can be manipulated like any other value:
▶ Example: Functions as Values
▶ Try it YourselfOutput:
# Function defined successfully
2. map(): Batch Transformation
map() applies a function to every element in a sequence and returns a new iterator:
▶ Example: map Batch Transform
▶ Try it YourselfOutput:
# Executed successfully
map()is equivalent to a list comprehension:map(f, seq)≈[f(x) for x in seq]. Which to use is a matter of preference — comprehensions are more "Pythonic."
3. filter(): Batch Filtering
filter() selects elements for which the function returns True:
▶ Example: filter Data
▶ Try it YourselfOutput:
# Executed successfully
filter()is also equivalent to a comprehension:filter(f, seq)≈[x for x in seq if f(x)]. UsingNoneas the function is equivalent to removing all falsy values ("",0,None,False, etc.).
4. Advanced sorted() Usage
Lesson 11 covered sorted()'s key parameter. Let's go deeper:
▶ Example: Custom Sorting with sorted
▶ Try it YourselfOutput:
# Executed successfully
▶ Example: Multi-Level Sorting (Difficulty ⭐⭐)
▶ Try it YourselfOutput:
Bob: 92
Diana: 92
Alice: 85
Charlie: 85
5. reduce(): Cumulative Computation
reduce() accumulates elements in a sequence, applying a function to two elements at a time. It's not a built-in; import from functools:
▶ Example: reduce Cumulative Computation
▶ Try it YourselfOutput:
# Executed successfully
(1) Execution Process of reduce()
# reduce(lambda x, y: x + y, [1, 2, 3, 4])
# Step 1: x=1, y=2 → 3
# Step 2: x=3, y=3 → 6
# Step 3: x=6, y=4 → 10
# Result: 10
reduce() vs loops: Anything reduce() can do, a for loop can also do. reduce() is more concise and declarative — you're saying "what to do" rather than "how to do it." The downside is it can be harder to understand for newcomers.
6. Lambda Expressions Deep Dive
Lambda, named after the Greek letter λ, is essentially an anonymous function — a small function without a name, used and discarded.
(1) Lambda vs Regular Functions
▶ Example: Lambda vs Regular
▶ Try it YourselfOutput:
# Function defined successfully
(2) Complete Lambda Syntax
lambda parameters: expression
# ↑ Equivalent to
def anonymous_function(parameters):
return expression
(3) Multiple Parameters
▶ Example: Lambda with Multiple Parameters
▶ Try it YourselfOutput:
# Executed successfully
(4) When to Use Lambda
▶ Example: Lambda Use Cases
▶ Try it YourselfOutput:
# Function defined successfully
7. Common Use Cases
- Data pipelines: Chain
map()→filter()→sorted()for data processing. - Custom sorting: Use
lambdaas thekeyparameter for various sort rules. - Event callbacks: Pass functions as arguments to GUI or web frameworks.
- Closure factories: Outer function returns inner function for "parameterized" functionality.
- Lazy evaluation: Higher-order functions defer computation until needed.
❓ FAQ
map() or list comprehensions?map() has advantages: ① Shorter when you have an existing function name (map(str.upper, seq) vs [s.upper() for s in seq]); ② Returns a lazy iterator, saving memory for large data. In most cases, list comprehensions are the better choice.reduce() still used in modern Python?📖 Summary
- Functions are first-class citizens in Python — can be assigned, passed, and returned
map(f, seq)applies a function to each element; uselist()to convert to a listfilter(f, seq)selects elements where the function returns Truesorted(seq, key=f)accepts a function for custom sortingreduce(f, seq)accumulates values; import fromfunctools- Lambda
lambda params: expressionis an anonymous single-line function for simple scenarios
📝 Exercises
-
Basic (Difficulty ⭐): Given
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], usemap()andfilter()to: filter odd numbers and compute their squares. Hint: Firstfilterfor odds, thenmapto square. -
Intermediate (Difficulty ⭐⭐): Given a list of dicts
products = [{"name": "A", "price": 100}, {"name": "B", "price": 80}, {"name": "C", "price": 120}], usesorted()to sort by price descending and output names and prices. -
Challenge (Difficulty ⭐⭐⭐): Use
reduce()to implement aflatten(nested_list)function that flattens a nested list by one level. For example,flatten([[1, 2], [3, 4], [5]])returns[1, 2, 3, 4, 5]. Hint: Inreduce, use+to merge two lists each time. Then implement the same with a list comprehension and compare the approaches.