Lambda Functions in Python
Lambdas are small, anonymous functions defined with lambda params: expr. They evaluate a single expression and return its value.
Basics
Use lambdas for short callbacks and functional pipelines.
add1 = lambda x: x + 1
mul = lambda a, b: a * b
They return the expression result implicitly.
When to use vs def
- Use
lambdafor tiny, inline functions - Use
deffor anything non‑trivial (multiple lines, statements, annotations, docstrings)
With higher‑order functions
Pass lambdas to sorted, map, filter, etc.
names = ["ada", "Guido", "Bjarne"]
print(sorted(names, key=lambda s: s.lower()))
Closures and late binding
Lambdas capture variables from the enclosing scope; late binding means the variable is looked up when the lambda runs.
funcs = [(lambda i=i: i) for i in range(3)] # capture current i via default
[f() for f in funcs] # [0,1,2]
Limitations
- Expression only: no statements (e.g., no assignment)
- Readability suffers beyond very simple cases; prefer
def
Alternatives
functools.partialfor binding some arguments
from functools import partial
pow2 = partial(pow, exp=2) # Python 3.8+: keyword-only in positional-only contexts may vary
Summary
- Lambdas are handy for short, inline functions
- Beware late binding; prefer
defwhen logic grows or needs documentation