Python 3 reference · Built-in Functions
Python max() Function
Return the largest item in an iterable, or the largest of several arguments. Supports a key function and a default.
Python 3 Since 3.0
Syntax
max(iterable, *, key=None, default)
max(arg1, arg2, *args, key=None)
Parameters
| Parameter | Description |
|---|---|
iterable / args |
One iterable, or two or more values. |
key optional |
A function that returns the value to compare, e.g. len. Default: None |
default optional |
Returned when the iterable is empty (otherwise ValueError). |
Return value
The largest item.
Examples
print(max(3, 9, 4))
print(max([2.5, 7.1, 0.3]))
print(max("banana")) # the "largest" character
Output
9 7.1 n
words = ["kiwi", "banana", "fig"]
print(max(words, key=len))
people = [{"name": "Ada", "age": 36}, {"name": "Linus", "age": 28}]
print(max(people, key=lambda p: p["age"])["name"])
Output
banana Ada
print(max([], default=0))
scores = {"Ada": 91, "Linus": 88}
print(max(scores, key=scores.get)) # the key with the highest value
Output
0 Ada
Common mistakes
max([]) raises ValueError: max() iterable argument is empty. Pass default= when the input may be empty.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.4 | Added the default parameter. |
| Python 3.8 | key can be None. |
Related
min()· Return the smallest item in an iterable, or the smallest of several arguments. Supports a key function and a default.sorted()· Return a new sorted list from any iterable. Supports a key function and reverse order; the original is left unchanged.sum()· Add up the numbers in an iterable, plus an optional start value. Floats are summed with extra precision since Python 3.12.- Python Lists · tutorial