Topic 60 of 64
Lambda Expression
Overview
Lambda creates anonymous single-expression functions. They are ideal for short callbacks in sorted(), map(), filter(), and similar higher-order function calls — keeping code concise without defining named functions.
Syntax
python
# lambda syntax: lambda params: expression
square = lambda x: x ** 2
square(5) # 25
add = lambda x, y: x + y
add(3, 4) # 7
# Most common use: as sort key
names = ["Charlie", "Alice", "Bob"]
sorted(names, key=lambda x: len(x)) # ['Bob', 'Alice', 'Charlie']
# With conditional expression
classify = lambda n: "even" if n % 2 == 0 else "odd"Common Pitfalls
- Lambdas are restricted to a single expression — no statements (no if blocks, no loops, no assignments).
- PEP 8 discourages assigning lambdas to variables — use def for named functions; lambda is for inline one-liners.
- Interview tip: Lambdas capture variables by reference, not value — this is the classic loop-lambda bug: [lambda: i for i in range(3)] all return 2 at call time.
Real-World Example
Sort a list of dicts by multiple criteria using lambda
example
python
products = [
{"name": "Widget", "price": 9.99, "stock": 50},
{"name": "Gadget", "price": 24.99, "stock": 10},
{"name": "Donut", "price": 1.99, "stock": 200},
{"name": "Gizmo", "price": 9.99, "stock": 100},
]
# Sort by price ascending, then by stock descending
sorted_products = sorted(
products,
key=lambda p: (p["price"], -p["stock"])
)
for p in sorted_products:
print(p["name"], p["price"], p["stock"])