Find a maximum
Choosing the greatest numeric value from a collection.
Python · Function
max() returns the largest item from an iterable or the largest among two or more positional arguments. Use key to control ordering and default to handle an empty iterable.
Use max() with one iterable argument to obtain its greatest item, or pass at least two positional values to compare those values directly. The keyword-only key function determines comparison values, while default supplies a result when an iterable has no items.
max(iterable, *, key=None, default=?)
max(arg1, arg2, *args, key=None)| Name | Type | Description |
|---|---|---|
iterable / arg1 | iterable or object | An iterable of candidates, or the first candidate when comparing multiple positional arguments. |
arg2, *args | object | Additional candidates to compare in the multiple-argument form. |
key | callable or None | A one-argument function used to determine ordering. |
default | object | Fallback returned when the iterable form receives no items. |
The largest item or argument according to the ordering rules; with key, it returns the original item associated with the greatest key result.
scores = [72, 91, 84]
print(max(scores))
print(max(scores, default=0))
print(max(["Ada", "Grace", "Linus"], key=len))The first call selects the greatest number, the second supplies a fallback for an empty iterable, and the third compares strings by their lengths.
Choosing the greatest numeric value from a collection.
Selecting an object by a derived property.
Making empty-input processing safe.
Comparing several independent candidate values.
With one positional argument, max() expects an iterable and returns its largest item. With two or more positional arguments, it compares those arguments directly.
Follow-up: How can max() choose the longest string? Pass key=len; max() compares the values returned by that one-argument function.
key is a one-argument ordering function. It transforms each candidate into a comparison value without changing which original item max() returns.
Follow-up: What happens when several items have equal key results? The first maximal item encountered is returned.
default is a keyword-only fallback used when the single iterable argument is empty. Without default in that situation, max() raises ValueError.
Follow-up: Can default be used with several positional candidates? No; it applies to the iterable form, not the multiple-argument form.
min()sorted()list.sort()heapq.nlargest()