Python max() and min() with key: Find the Largest and Smallest Elements Smartly
- Home
- Python max() and min() with key: Find the Largest and Smallest Elements Smartly
max() and min() with key – Find the Largest and Smallest ElementsWhen working with flat lists of numbers or strings, Python’s built-in max() and min() work out of the box using default comparisons. However, when dealing with lists of dictionaries, tuples, or custom objects, passing the key parameter lets you define the exact comparison rule without writing manual loops or sorting the entire collection.
Here is how to use max() and min() with key for clean, readable, and efficient Python code.
max(iterable, *, key=None, default=...)
min(iterable, *, key=None, default=...)
iterable: Any iterable collection (list, tuple, set, generator, etc.).
key: A single-argument function (commonly a lambda or built-in function) that extracts the comparison value from each element.
default: A fallback value returned when iterable is empty, preventing a ValueError.
orders = [
{"id": "ORD-01", "total": 450},
{"id": "ORD-02", "total": 1250},
{"id": "ORD-03", "total": 780},
]
highest_order = max(orders, key=lambda item: item["total"])
lowest_order = min(orders, key=lambda item: item["total"])
print(highest_order) # {'id': 'ORD-02', 'total': 1250}
print(lowest_order) # {'id': 'ORD-01', 'total': 450}
endpoints = ["/health", "/api/v1/users", "/api/v1/notifications/mark-all-read"]
shortest = min(endpoints, key=len)
longest = max(endpoints, key=len)
print(shortest) # /health
print(longest) # /api/v1/notifications/mark-all-read
When multiple elements share the top primary value, returning a tuple from key establishes clear tie-breaking priority. For example, find the highest-rated product, breaking ties by the lowest price:
products = [
{"name": "Keyboard A", "rating": 4.8, "price": 150},
{"name": "Keyboard B", "rating": 4.8, "price": 110},
{"name": "Keyboard C", "rating": 4.9, "price": 220},
]
# Highest rating first -> lowest price second (negate numeric price)
best_pick = max(products, key=lambda p: (p["rating"], -p["price"]))
print(best_pick["name"]) # Keyboard C
Always pass default for dynamic collections: Calling max([]) on an empty filtered list raises ValueError: max() arg is an empty sequence. Provide default=None or an appropriate fallback value.
Prefer max() / min() over sorted()[0]: Finding a single extreme runs in $O(n)$ linear time with constant memory overhead, whereas sorting the entire sequence takes $O(n \log n)$.
Original elements are returned intact: The key function only determines how elements are compared—max() and min() still return the original item (dictionary, tuple, or object), not the computed key value.
| Goal | Pattern |
| Find by dictionary field | max(items, key=lambda x: x["score"]) |
| Find longest or shortest string | max(words, key=len) / min(words, key=len) |
| Guard against empty iterables | max(items, key=..., default=None) |
| Break ties across multiple fields | max(items, key=lambda x: (x["a"], x["b"])) |