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.


Related Built-in Functions:filter() sorted() list() lambda map() max() sum() False True None

1. Functions Are First-Class Citizens

In Python, functions can be manipulated like any other value:

▶ Example: Functions as Values

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully
💡 What does "functions are first-class citizens" mean? It means functions are on the same level as integers, strings, and lists — you can assign them to variables, put them in lists, pass them as arguments, and return them as values. This programming paradigm is called "functional programming."



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 Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

filter() is also equivalent to a comprehension: filter(f, seq) ≈ [x for x in seq if f(x)]. Using None as 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

▶ Example: Multi-Level Sorting (Difficulty ⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

(1) Execution Process of reduce()

PYTHON
# 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 Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

(2) Complete Lambda Syntax

PYTHON
lambda parameters: expression
# ↑ Equivalent to
def anonymous_function(parameters):
    return expression

(3) Multiple Parameters

▶ Example: Lambda with Multiple Parameters

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

(4) When to Use Lambda

▶ Example: Lambda Use Cases

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully
💡 Lambda rule of thumb: If the logic needs more than one expression or if-elif branching, don't use lambda — write a regular function instead. Lambda's elegance is in its "minimalism."



7. Common Use Cases


Related Built-in Functions:filter() sorted() list() lambda map() max() sum() False True None

❓ FAQ

Q Which is better — map() or list comprehensions?
A The Python community prefers list comprehensions — more intuitive, more Pythonic. 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.
Q Can lambda span multiple lines?
A No. Lambda syntax is restricted to single expressions. For multi-line logic, define a regular function. Python's lambda is deliberately weaker than in other languages (like JavaScript) — Guido (Python's creator) believes "explicit is better than implicit."
Q Is reduce() still used in modern Python?
A Not very much. Guido himself wasn't fond of reduce(), finding it hard to understand. Most reduce() scenarios can be replaced with a loop or a more direct function (like sum(), max()). However, reduce() remains an important concept in functional programming.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Given nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], use map() and filter() to: filter odd numbers and compute their squares. Hint: First filter for odds, then map to square.

  2. Intermediate (Difficulty ⭐⭐): Given a list of dicts products = [{"name": "A", "price": 100}, {"name": "B", "price": 80}, {"name": "C", "price": 120}], use sorted() to sort by price descending and output names and prices.

  3. Challenge (Difficulty ⭐⭐⭐): Use reduce() to implement a flatten(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: In reduce, use + to merge two lists each time. Then implement the same with a list comprehension and compare the approaches.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏