In Python, max() returns the largest item, either of one iterable, max([3, 11, 7]), or of two or more arguments, max(3, 11, 7).
Like min(), it accepts a key function to choose what is compared, returns the first of several equal maximums, and accepts default for an empty iterable. Strings, tuples, and lists compare item by item from the left.
max() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Use the same call shapes as min().
python
largest = max(iterable, key=None)
largest = max(a, b, c)
largest = max(iterable, default=value)
Call
What it does
max(3, 11, 7)
Returns 11.
max(scores, key=abs)
Returns the score farthest from zero.
max(d, key=d.get)
Returns the dict key with the largest value.
max(low, min(x, high))
Clamps x into the range low..high.
max(5) is an error: with one argument, max() expects an iterable, and an int is not iterable.
Top student: Mei
Most common: kiwi 9
Longest: yellow
How It Works
Score as key. The lambda pulls out each student's score; the dict with the highest score is returned.
First of a tie. Mei and Tom both have 95, and Mei comes first, so Mei is the top student.
Dict lookup key.key=word_counts.get compares the counts and returns the key "kiwi".
Length key."yellow" has 6 letters, more than "red" or "blue".
Example 3 — Clamp a Value into a Range
Combine max() and min() to keep a value between limits, then look at empty and single-int calls.
python
def clamp(value, low, high):
return max(low, min(value, high))
for v in [-5, 42, 150]:
print(v, "->", clamp(v, 0, 100))
print(max([], default=0))
try:
max(5)
except TypeError:
print("max(5) fails: a single int is not iterable")
Output
-5 -> 0
42 -> 42
150 -> 100
0
max(5) fails: a single int is not iterable
How It Works
Upper limit.min(value, high) caps 150 at 100.
Lower limit.max(low, ...) lifts -5 up to 0; 42 is inside the range and passes through.
Safe empty case.max([], default=0) returns the default instead of raising ValueError.
One argument must be iterable.max(5) tries to loop over 5 and raises TypeError.
Frequently Asked Questions
Call max(numbers). Use max(numbers, default=None) if the list might be empty.
Use numbers.index(max(numbers)), or max(range(len(numbers)), key=numbers.__getitem__) to avoid a second pass.
max(d, key=d.get) returns the key. max(d.values()) returns only the value.
The first maximal item encountered, in iteration order.
Yes. Strings compare character by character by Unicode code point, so max("apple", "banana") is "banana". Use key=str.lower for case-insensitive comparison.