runtime
70 / 250
lesson 70 Built-ins & Sorting · intermediate

Totals and extremes with sum, min and max

`sum` adds a collection up; `min` and `max` find its extremes. With `key` they return the whole winning record, and with `default` they survive an empty input.

You'll be able to
  • Total a field with sum(x["field"] for x in items)
  • Find the record with the smallest or largest field using min(items, key=…) and max(items, key=…)
  • Handle an empty input with default= instead of letting ValueError stop the program
The idea

Totals and extremes are the most common questions in reporting: the invoice subtotal, the cheapest product, the fastest lap. sum, min and max each take a collection, often a generator expression, and return one value.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · An invoice summary
lines = [
    {"sku": "SPO-11681", "qty": 2, "price": 7.5},
    {"sku": "HOM-22847", "qty": 1, "price": 31.0},
    {"sku": "ELE-24781", "qty": 1, "price": 171.25},
]
units = sum(line["qty"] for line in lines)
subtotal = sum(line["qty"] * line["price"] for line in lines)
print(units, subtotal)
print(min(line["price"] for line in lines), max(line["price"] for line in lines))

min and max of nothing has no answer, so Python stops with an error rather than inventing one.

example-2.py · The largest of nothing
delays = []
print(max(delays))

To get the record rather than the number, pass the records and a key, exactly as with sorted. On a tie, the first record wins. default= is returned when the input is empty, which turns *no data* into a value you can test, such as None.

example-3.py · Fastest lap, slowest driver, no laps
def lap_seconds(lap):
    return lap["seconds"]

laps = [
    {"driver": "Ana", "seconds": 92.4},
    {"driver": "Ben", "seconds": 91.8},
    {"driver": "Chen", "seconds": 91.8},
]
best = min(laps, key=lap_seconds)
print(best["driver"], best["seconds"])
print(max(laps, key=lap_seconds)["driver"])
print(min([], key=lap_seconds, default=None))

When to use it: any total, smallest or largest. Mistakes to avoid: expecting max(x["price"] for x in items) to give you the product (it gives the price; use key for the product); min/max on something that may be empty without default; and sum of texts, which raises TypeError. A tuple key settles ties on purpose: min(routes, key=minutes_then_price).

Review
  • sum(...) totals; min/max return the extreme value, or the extreme record with key=.
  • On a tie, min and max return the first item; a tuple key settles ties on purpose.
  • min/max of nothing raise ValueError unless you pass default=.
  • Next module: functions that take any number of arguments, keyword-only options, small inline functions, closures and recursion.
Practise this

Loading your progress…

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

Totals and extremes with sum, min and max — Built-ins & Sorting · Runtime