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.
- Total a field with
sum(x["field"] for x in items) - Find the record with the smallest or largest field using
min(items, key=…)andmax(items, key=…) - Handle an empty input with
default=instead of letting ValueError stop the program
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.
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.
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.
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).
sum(...)totals;min/maxreturn the extreme value, or the extreme record withkey=.- On a tie,
minandmaxreturn the first item; a tuple key settles ties on purpose. min/maxof nothing raise ValueError unless you passdefault=.- Next module: functions that take any number of arguments, keyword-only options, small inline functions, closures and recursion.