How does a `lambda` expression differ from a regular function defined with `def`, and when should you avoid a lambda?
Answer
A `lambda` is an anonymous function whose body is restricted to a single expression, not a block of statements: it cannot contain `for`/`while` loops, `if` statements, or assignment statements, and it implicitly returns the value of that one expression — though the expression itself can still use expression-level constructs like a conditional expression (`a if cond else b`), a comprehension, or the walrus operator `:=`, since those are expressions rather than statements. A `def` function can hold multiple statements, docstrings, type annotations and a proper `__name__`. Prefer `def` whenever the logic needs more than a single expression, needs a docstring for maintainability, or would otherwise be assigned to a variable, since PEP 8 explicitly discourages binding a lambda to a name instead of just using `def`.
Strong answer includes
- lambda body is a single expression, not a block of statements
- def supports multiple statements, docstrings, and a real name
- PEP 8 discourages assigning a lambda to a variable name
Practical example
Run the code to see the result.
A lambda is concise for a disposable single expression such as a sort key. A named def is clearer once logic needs documentation, reuse, annotations, or multiple statements.
Expected result: Both sorts put the item with duration 2 before the item with duration 8.