min And max Accept Key Functions And Defaults

min and max take a key function to rank derived values and a default to answer empty sequences instead of raising ValueError; the original objects come back.

PythonData Integrity

Code

pythonsnippet
23 lines
users = [
    {"name": "ada", "score": 91},
    {"name": "linus", "score": 78},
    {"name": "grace", "score": 84},
]

# key= makes min/max compare by a derived value; the original object is returned
best = max(users, key=lambda u: u["score"])
print("top scorer:", best["name"], best["score"])

shortest = min(users, key=lambda u: len(u["name"]))
print("shortest name:", shortest["name"])

# An empty sequence raises ValueError; default= supplies a fallback instead
empty = []
print("max of empty with default:", max(empty, default=0))
try:
    max(empty)
except ValueError as exc:
    print("without default:", exc)

# key and default combine: nothing to pick, so the default comes back
print("min of empty by key:", min(empty, key=lambda u: u["score"], default=None))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

top scorer: ada 91
shortest name: ada
max of empty with default: 0
without default: max() arg is an empty sequence
min of empty by key: None

How the snippet works

The file’s state is a handful of top-level bindings: users, best, shortest, empty.

Points of care

  • Zero third-party dependencies — the runtime provides every API used here.

Applying it

Expect labeled output — top scorer:, shortest name:, max of empty with default: — when the file runs.

Statements that carry the logic

except ValueError as exc:
    print("without default:", exc)

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `users`, `best`, `shortest`.