List and dict comprehensions transform collections in one line. Lambda functions do the same for small, throwaway functions—anonymous one-expression functions you pass to sorted(), map(), filter(), and Pandas apply() without defining a full def block.
In AI codebases, lambdas appear when ranking retrieval results by score, sorting hyperparameter trials, or applying a quick normalization step. They are not a replacement for named functions, but they eliminate boilerplate when the logic is truly trivial.
Learning Objectives
By the end of this lesson, students should be able to:
- Define lambda functions with the
lambda arguments: expressionsyntax. - Pass lambdas to
sorted(),map(), andfilter(). - Distinguish when a lambda is appropriate versus when a named function improves readability.
- Understand that lambdas are limited to a single expression (no statements or assignments).
- Recognize lambdas in library APIs such as Pandas
df.apply(lambda x: ...).
Introduction: Functions Without Names
A lambda (also called an anonymous function) is a compact function defined inline. Python evaluates the expression and returns its value—no return keyword needed.
lambda parameters: expression
Equivalent to a one-line def that immediately returns the expression.
# Named function
def square(n):
return n ** 2
# Lambda equivalent
square = lambda n: n ** 2
# Typical usage: pass directly without binding
nums = [3, 1, 4, 1, 5]
sorted(nums, key=lambda x: -x) # descending: [5, 4, 3, 1, 1]
Common Patterns in AI Workflows
chunks = [
{"text": "policy section A", "score": 0.71},
{"text": "policy section B", "score": 0.93},
{"text": "policy section C", "score": 0.58},
]
top = sorted(chunks, key=lambda c: c["score"], reverse=True)[:2]
| Built-in | Lambda Role | Example |
|---|---|---|
sorted() | Sort key | sorted(rows, key=lambda r: r["loss"]) |
map() | Transform each item | list(map(lambda x: x.lower(), tokens)) |
filter() | Keep items matching condition | list(filter(lambda x: len(x) > 0, texts)) |
max() / min() | Comparison key | max(trials, key=lambda t: t["f1"]) |
Use a Lambda
- Single expression, used once
- Passed as a callback to
sortedorapply - Logic is obvious at the call site
Use a Named def
- Multiple statements or error handling
- Reused in several places
- Needs a docstring or unit tests
Reality: Lambdas accept only a single expression. You cannot use if/else blocks (though a conditional expression a if cond else b is allowed), loops, or return statements. For richer logic, define a regular function.
Knowledge Check
- Write: Lambda that doubles its argument. Answer:
lambda x: x * 2 - True/False: Lambdas can have multiple parameters. Answer: True (
lambda a, b: a + b). - Short Answer: What does
sorted(words, key=len)use instead of a lambda? Answer: The built-inlenfunction as the key. - Multiple Choice: Best choice for a 15-line preprocessing function: (a) lambda, (b) def, (c) comprehension only, (d) global variable. Answer: (b).
- Short Answer: What is the lambda syntax pattern? Answer:
lambda parameters: expression. - True/False: Lambdas can contain loops and assignment statements. Answer: False—only a single expression is allowed.
- Short Answer: How would you sort retrieval chunks by
scoredescending with a lambda? Answer:sorted(chunks, key=lambda c: c["score"], reverse=True). - Multiple Choice: Pandas one-off column transform often uses: (a)
df.apply(lambda x: ...), (b) CUDA kernels only, (c) HTML, (d) regex compilation. Answer: (a). - True/False: A conditional expression
a if cond else bis allowed inside a lambda. Answer: True. - Short Answer: When should you prefer a named
defover a lambda? Answer: Multiple statements, reuse, docstrings, or unit tests.
Key Takeaways
- Lambdas are single-expression anonymous functions.
- They shine as short callbacks for sorting, mapping, and filtering.
- Readability degrades quickly—prefer named functions for non-trivial logic.
- Next: *args and **kwargs for flexible function signatures used throughout ML libraries.
Refactoring drill: Present a three-line def used only once in sorted(). Ask students to convert it to a lambda and discuss whether readability improved or worsened.
Recap: Lambdas are single-expression callbacks for sorting, mapping, and filtering; next, flexible signatures in *args and **kwargs.