Coding Techniques
Lambda Functions · Study material
A dispatch table of lambdas
A dictionary that maps operators to small lambdas replaces a long if-elif chain and is easy to extend.
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b if b else float("nan"),
"**": lambda a, b: a ** b,
}
for expr in ["7 + 3", "7 / 2", "2 ** 8", "5 / 0"]:
a, op, b = expr.split()
print(expr, "=", ops[op](float(a), float(b)))
7 + 3 = 10.0 7 / 2 = 3.5 2 ** 8 = 256.0 5 / 0 = nan
Lambda, def or comprehension?
| Situation | Best choice |
|---|---|
| A one-off key for sorted / min / max | lambda (or itemgetter) |
| Transforming or filtering a list | a list comprehension |
| Applying an existing named function | map(func, items) |
| Logic needing several steps, a loop or try | def |
| A function reused in several places | def with a docstring |
Avoiding the late-binding trap
buttons = {}
for label in ["Save", "Open", "Exit"]:
buttons[label] = lambda: print("clicked", label) # ✘ all print "Exit"
for label in ["Save", "Open", "Exit"]:
buttons[label] = lambda label=label: print("clicked", label) # ✔ value frozen
from functools import partial
for label in ["Save", "Open", "Exit"]:
buttons[label] = partial(print, "clicked", label) # ✔ partial also freezes it Lambda checklist
- Keep lambdas to one short, obvious expression.
- Use them inline (key=, map, filter), not assigned to names.
- Return tuples from key functions for multi-field sorts.
- Freeze loop variables with a default argument.
- Wrap map/filter in list() if you need the values twice.
- Give reduce() an initial value when the input may be empty.