Inline functions with lambda
`lambda` writes a small function as one expression, right where it is passed, such as a sort key. A function that deserves a name is written with `def`.
- Write
key=lambda item: item["field"]forsorted,minandmax - Pass a lambda to your own function that takes a function
- Know the limits: one expression, no statements, and never
name = lambda …
In the Built-ins & Sorting module every sort key was a def written somewhere above the call and used once. lambda writes the same function inline: lambda r: r["date"] takes one parameter, r, and returns the expression after the colon. There is no return; the expression is the result.
Run each example to see what it prints. Running examples doesn't count toward progress.
readings = [
{"station": "Boston Logan", "date": "2025-01-14", "tmax": 3.9},
{"station": "Atlanta Hartsfield", "date": "2025-01-12", "tmax": 11.7},
{"station": "Great Falls Airport", "date": "2025-01-14", "tmax": -12.2},
]
by_date = sorted(readings, key=lambda r: r["date"])
print([r["station"] for r in by_date])
coldest = min(readings, key=lambda r: r["tmax"])
print(coldest["station"], coldest["tmax"])A lambda is a full function value, so it can go to your functions too. A function that takes a key function can group, count or filter by any rule the caller chooses.
def group_by(flights, key): groups = {} for flight in flights: k = key(flight) if k not in groups: groups[k] = [] groups[k].append(flight["flight"]) return groups flights = [ {"flight": "UA2017", "origin": "LAS", "arrival_delay": -4}, {"flight": "MQ3615", "origin": "FAR", "arrival_delay": 42}, {"flight": "UA1552", "origin": "LAS", "arrival_delay": 16}, ] print(group_by(flights, lambda f: f["origin"])) print(group_by(flights, lambda f: f["arrival_delay"] >= 15))
A lambda holds one expression. Statements such as return, if blocks or assignments are not allowed inside it.
invoices = [{"id": "INV-1", "due": "2025-01-31"}]
print(sorted(invoices, key=lambda inv: return inv["due"]))When to use it: a short key or rule used once, right in the call. When not to: if the function needs a name, several steps, or will be reused, write a def. In particular, never write price_of = lambda p: p["price"]: that is a def with a worse name (<lambda> in error messages) and no room for a docstring. Python's style guide (PEP 8) says the same. Prefer a comprehension over map(lambda …) and filter(lambda …).
lambda x: expressionis a one-expression function, written inline where it is passed.- Use it for short keys and rules (
sorted,min,max, your ownkeyparameters). - Never assign a lambda to a name: write a
def. Statements are not allowed in a lambda. - Next: functions that build and return other functions, which remember values.