Python Reference ยท Built-in Functions
Python max() function
Reference for Python max(): find the largest item of an iterable or among arguments, key functions, the default for empty input, ties and comparing strings.
The max() function returns the largest item. You can pass one iterable (max([3, 9, 4])) or several separate arguments (max(3, 9, 4)). What counts as "largest" is decided by the < ordering of the items, or by a key function that you supply.
The key argument is what makes max() so flexible: you can pick the longest word, the most expensive product, or the dictionary entry with the highest score.
print(max(3, 9, 4)) # 9 print(max(["pear", "fig"], key=len)) # pear
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
max(iterable, *, key=None, default=<no default>) max(arg1, arg2, *args, key=None)
| Name | Description |
|---|---|
iterable |
The items to compare. Must be non-empty unless default is given. |
arg1, arg2, *args |
Separate values to compare (two or more). |
key |
Optional one-argument function. Items are compared by key(item), and the original item is returned. |
default |
Optional keyword-only value returned when the iterable is empty. Not allowed with separate arguments. |
Return value: the largest item (not the key value).
Raises: ValueError for an empty iterable without default; TypeError if items can't be compared (such as 3 and "a"), or if default is used with multiple arguments.
Usage notes
- First wins on ties. If several items compare equal,
max()returns the first one it saw.min()behaves the same way. - Tuples compare element by element, which is useful for tie-breaking:
max(people, key=lambda p: (p.age, p.name)). - Strings compare by code point, so
"Zebra" < "apple"andmax(["apple", "Zebra"])is'apple'. Usekey=str.lowerfor case-insensitive comparison. - Dictionaries iterate keys. To get the key with the biggest value use
key=d.get; to get the value usemax(d.values()). - Iterators are consumed.
max()on a generator uses it up. - Not NaN-safe. Comparisons with
float("nan")are always false, so results depend on position; clean the data first. - Need the index? Use
max(range(len(seq)), key=seq.__getitem__), or enumerate with a key. - Top N. For the several largest items use
heapq.nlargest()orsorted(..., reverse=True)[:n].
Related
min(),sorted(),sum(),len(),abs()- Lessons: Lists, Higher-order functions, Dictionaries