runtime
73 / 250
lesson 73 Advanced Functions & Recursion · intermediate

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`.

You'll be able to
  • Write key=lambda item: item["field"] for sorted, min and max
  • Pass a lambda to your own function that takes a function
  • Know the limits: one expression, no statements, and never name = lambda …
The idea

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.

example-1.py · Keys written where they are used
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.

example-2.py · Group flights by any rule
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.

example-3.py · A statement inside a lambda
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 …).

Review
  • lambda x: expression is a one-expression function, written inline where it is passed.
  • Use it for short keys and rules (sorted, min, max, your own key parameters).
  • 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.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Inline functions with lambda — Advanced Functions & Recursion · Runtime