← Master Index
Vol. 03 Module 3.4 Lecture

Lambda Functions

Essential Python Skills for AI Engineers (added — needed in practice, not in original outline)

How This Lesson Fits the Module

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: expression syntax.
  • Pass lambdas to sorted(), map(), and filter().
  • 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.

Definition — Lambda Syntax

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

AI Example — Sorting Retrieval Results
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-inLambda RoleExample
sorted()Sort keysorted(rows, key=lambda r: r["loss"])
map()Transform each itemlist(map(lambda x: x.lower(), tokens))
filter()Keep items matching conditionlist(filter(lambda x: len(x) > 0, texts))
max() / min()Comparison keymax(trials, key=lambda t: t["f1"])

Use a Lambda

  • Single expression, used once
  • Passed as a callback to sorted or apply
  • 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
Common Misconception: “Lambdas can contain any Python code.”

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

  1. Write: Lambda that doubles its argument. Answer: lambda x: x * 2
  2. True/False: Lambdas can have multiple parameters. Answer: True (lambda a, b: a + b).
  3. Short Answer: What does sorted(words, key=len) use instead of a lambda? Answer: The built-in len function as the key.
  4. Multiple Choice: Best choice for a 15-line preprocessing function: (a) lambda, (b) def, (c) comprehension only, (d) global variable. Answer: (b).
  5. Short Answer: What is the lambda syntax pattern? Answer: lambda parameters: expression.
  6. True/False: Lambdas can contain loops and assignment statements. Answer: False—only a single expression is allowed.
  7. Short Answer: How would you sort retrieval chunks by score descending with a lambda? Answer: sorted(chunks, key=lambda c: c["score"], reverse=True).
  8. 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).
  9. True/False: A conditional expression a if cond else b is allowed inside a lambda. Answer: True.
  10. Short Answer: When should you prefer a named def over 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.
Trainer’s Guide

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.