max() can be called two ways: with a single iterable, or with two or more separate arguments. The optional key function lets you rank items by something other than their natural ordering — for example, finding the longest string in a list instead of the alphabetically last one. default supplies a fallback value instead of raising ValueError when the iterable is empty.
1Understanding max()
max() can be called two ways: with a single iterable, or with two or more separate arguments. The optional key function lets you rank items by something other than their natural ordering — for example, finding the longest string in a list instead of the alphabetically last one. default supplies a fallback value instead of raising ValueError when the iterable is empty.
Pass default=... to max() to avoid a crash when the iterable might be empty — always consider whether that's possible.
scores = [88, 95, 72, 100, 61]
print(max(scores))2Practical Example
Here is a real-world application of max() showing how it is used in production Python code.
students = [{"name": "Ana", "score": 91}, {"name": "Boris", "score": 87}]
top = max(students, key=lambda s: s["score"])
print(top["name"])3Best Practices
Follow these guidelines when working with max():
1. Use the key= parameter instead of manually looping to find the item with the largest computed property
2. Pass default=... when the iterable could plausibly be empty, to avoid a crash
3. Use max(a, b) for two plain values instead of an if/else comparison
Tip: Pass default=... to max() to avoid a crash when the iterable might be empty — always consider whether that's possible.
scores = [88, 95, 72, 100, 61]
print(max(scores))