Lambda Functions#
Lambda expressions create small anonymous functions: lambda args: expression. They are expressions (not statements) — useful for short callbacks and key= functions.
How to use this page
Use lambdas for one-liners; use def when logic grows. See Higher Order Functions.
At a glance
| Track | Python Advanced → Advanced Functions |
| Sections | 5 major topics |
| Outline | Use the right-hand TOC to jump |
Topics: Syntax · Common uses · Lambda vs def · Closures with lambda · Alternatives
- Syntax
- Common uses
- Lambda vs
def - Closures with lambda
- Alternatives
Syntax#
lambda x: x * 2
lambda x, y: x + y
lambda: 42
lambda *args: sum(args)
lambda x, y=10: x + y # default allowed
Restrictions:
- Body is one expression — no statements, no assignments (until walrus in expression context)
- No annotations on parameters (use
deffor typed APIs) - No docstring
Common uses#
Sorting keys#
map / filter#
Prefer comprehensions when readable:
Delayed callbacks#
Lambda vs def#
lambda |
def |
|
|---|---|---|
| Name | Anonymous | Named |
| Body | Single expression | Statements |
| Tracebacks | Shows <lambda> |
Shows function name |
| Debugging | Harder | Easier |
| Best for | key=, short callbacks |
Everything non-trivial |
Rule: if it doesn't fit on one line comfortably, use def.
Closures with lambda#
Same late-binding rules as nested def — see Closures.
Alternatives#
# operator module — no lambda needed
from operator import itemgetter, attrgetter
sorted(rows, key=itemgetter(1))
sorted(users, key=attrgetter("name"))
# partial
from functools import partial
double = partial(pow, 2) # careful: pow(2, x) vs pow(x, 2)
Interview traps (quick reference)#
| Trap | What goes wrong | Safe approach |
|---|---|---|
| Lambda in loop without bind | All use final loop var | lambda i=i: or factory |
| Complex lambda | Unreadable | def helper |
| Statement in lambda | SyntaxError | Use def |
| Side effects in lambda | Hard to test | Named function |
Mental model checklist#
- What can a lambda body contain?
- When is
operator.itemgetterbetter than lambda? - Why name lambdas in loop callbacks carefully?
What's next#
| Topic | Page |
|---|---|
| Higher-order functions | Higher Order Functions |
| Partial | Partial Functions |
| Closures | Closures |