Home / Python / Reference / Built-in functions

Python max() function

Return the largest item.

Syntax

max(iterable, *, key=None, default=...) / max(a, b, ...)

Give it a collection or several values. With key, it compares a computed value for each item, such as the length of a word or one field of a record. default is returned for an empty collection instead of an error.

Parameters

iterablethe items to compare
keya function that gives the value to compare
defaultreturned if the iterable is empty

Return value

the largest item

Example

Code

print(max([3, 9, 2]))
print(max(3, 9, 2))
print(max(["kiwi", "banana", "fig"]))            # alphabetical
print(max(["kiwi", "banana", "fig"], key=len))   # longest
people = [("Sita", 27), ("Leo", 31)]
print(max(people, key=lambda p: p[1]))
print(max([], default=0))

Output

9
9
kiwi
banana
('Leo', 31)
0
Good to know. max([]) raises ValueError; give a default.

Related

Learn it step by step in the free lesson More Functions, with exercises that check your answers.