compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
def vs lambda
Sort words by length, then alphabetically.
what differs
Both create function objects. A lambda is limited to one expression and is anonymous (its __name__ is '<lambda>', which shows up in tracebacks).
at a glance
| approach | use it when |
|---|---|
| A · def | The logic has a name worth giving, is reused, needs a docstring or more than one expression. |
| B · lambda | A tiny, one-off function passed straight to another call. |
Watch out: Lambdas in a loop capture variables, not values: [lambda: i for i in range(3)] all return 2. Bind with lambda i=i: i.
the outputs
Each approach runs on the same input.
concepts
first-class functionsclosures
learn it
Define a function and call it · Pure functions: same input, same output, no surprises
related comparisons