MOD-17 · Sequence #17 · Functions & Modules

Python Lambda Functions

Lambda functions are small, anonymous, single-expression functions defined with the lambda keyword. They are commonly used as key extractors in sorted(), max(), and min(), or in functional tools like map() and filter().

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16]

Core Principles & Mental Models

1. Syntax and Limitations of Lambdas

Single Expression, Implicit Return

  • Syntax: `lambda arguments: expression`.
  • Lambdas can take any number of arguments, but can only contain a single expression — no statements, loops, or assignments.
  • The result of the expression is implicitly returned.
square = lambda x: x ** 2
print("5 squared:", square(5))
💡 Key Takeaway: Use lambdas for short inline helpers; use def statements for any multi-line or documented logic.

2. Higher-Order Functions: map(), filter(), sorted()

Passing Functions as First-Class Values

  • `sorted(iterable, key=lambda x: ...)` sorts elements based on the extracted key.
  • `filter(func, iterable)` yields elements where func returns Truthy.
  • `map(func, iterable)` applies func to every item in the sequence.
words = ["elephant", "cat", "hippopotamus", "dog"]
# Sort by string length
by_length = sorted(words, key=lambda w: len(w))
print("Sorted by length:", by_length)
💡 Key Takeaway: Lambdas excel as inline keys for custom sorting and aggregation.

Interactive Walkthrough Examples

Sorting Complex Tuples by Multiple Keys (Intermediate)

Using lambda to sort by primary and secondary criteria.

students = [
    ("Alice", 90, 2),
    ("Bob", 95, 1),
    ("Charlie", 90, 1)
]
# Sort by score descending (-score), then by rank ascending
sorted_students = sorted(students, key=lambda s: (-s[1], s[2]))
for name, score, rank in sorted_students:
    print(f"{name}: Score {score}, Rank {rank}")

Explanation: Returning a tuple (-s[1], s[2]) allows multi-level sorting in a single pass.

Common Misconceptions & Exam Traps

Common Pitfall: Binding Lambdas to Names Instead of Using `def` (PEP 8 Violation)

PEP 8 specifies that named functions should always use `def` because tracebacks show `<lambda>` instead of meaningful function names.

Buggy Code
f = lambda x, y: x + y  # Discouraged by PEP 8
Correct Solution
def f(x, y):           # Better for traceback stack traces and docstrings
    return x + y

Exam Trap Note: In code reviews, assigning a lambda to a variable name is flagged as poor style.

Conceptual Knowledge Self-Check Quiz

Q1: Which of the following statements CANNOT be placed inside a Python lambda?

  1. An arithmetic calculation
  2. A ternary conditional expression (x if c else y)
  3. A while loop or assignment statement
  4. A function call

Python lambdas can only contain a single expression; statements like while loops, for loops, and assignments are syntactically forbidden.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Use list comprehensions instead of `list(map(lambda ...))` for readability.
  • ✅ Use `operator.itemgetter` and `operator.attrgetter` as faster alternatives to lambdas for key extraction.

All 26 Curriculum Modules