18 · Lambda functions
Anonymous one-liners for sorted, map, filter, and df.apply — and when a named def is the better call.
`lambda params: expression` creates a nameless function in-place — perfect for a one-off key function passed to `sorted()`, `map()`, or `filter()` where a full `def` would be more ceremony than code.
Without this:
Without lambdas, every inline key function for sorting or filtering requires a named `def` three lines above the call — fragmenting the logic across the file and making it harder to read sorting intent at a glance.
lambda parameters: expression is syntactic sugar for a simple function that consists of a single expression — no def, no return, no body. The result of the expression is returned automatically. Lambdas are most useful as inline key functions for sorted(), min(), max(), map(), filter(), and Pandas df.apply(). They should stay short: if you need more than one expression, or you want to reuse the function, give it a name with def.
Python (in browser)
`key=lambda x: x[1]` tells `sorted` how to extract the comparison key from each element — the sort is by that key, not by the whole tuple. One line, reads like prose.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
When a lambda would need a comment to be understood, write a `def` instead. The function name becomes free documentation — and shows up in tracebacks with a readable name instead of `<lambda>`.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
PEP 8 and ruff rule `E731` prohibit assigning a lambda to a name — use `def` instead. Lambdas belong inline, not as named variables.
What does `(lambda x: x * 2)(5)` evaluate to?
- `lambda params: expr` — anonymous single-expression function. Ideal as an inline `key=` for `sorted()`, `min()`, `max()`, `map()`, `filter()`, or `df.apply()`.
- When the logic needs a comment, needs reuse, or is longer than one expression — write a `def` instead. Named functions have docstrings, readable tracebacks, and no linter warnings.
- Never assign a lambda to a name (`fn = lambda x: ...`). ruff/flake8 flag this as E731 — the `def` form is always better.
Ranking checkpoints by validation loss: `sorted(history, key=lambda h: h['val_loss'])`. Creating a custom scorer in scikit-learn: `make_scorer(lambda y, yp: -mse(y, yp))`. One-off Pandas column transforms: `df['score_pct'] = df['score'].apply(lambda x: round(x * 100, 1))`. These inline lambdas keep the surrounding pipeline readable without polluting the module namespace.
If you remove it: Without lambdas, every inline sort key or one-off transform requires a named function defined elsewhere in the file. For exploratory notebooks this fragmenting of intent across cells makes the code harder to follow and review.