Python max() Function

Returns the largest value in a list of parameters or in an iterable.

Syntax

Python
max(iterable1, iterable2, ..., key = None, default = None)
max(item1, item2, ..., key = None)

Parameters

ParameterDescription
iterable1, iterable2, ... Required. A list of iterables containing the items to be compared. In this form at least one iterable must be passed to the function, and the largest item from all items in all iterables will be returned.
item1, item2, ... Required. A list of items to be compared. In this form at least 2 items must be passed to the function.
key Optional. A function that returns, for each item, a representative value for that item for use in the comparison.
default Optional. If the iterable is empty then this value is returned.

Example

Python
print(max(1, 3, 2))
nums = [10, 40, 30, 20]
print(max(nums))

Output

3
40

Notes

If the iterable is empty, max() will throw a ValueError exception unless a default value is provided:

Example:
Python
try:
    max([])
except ValueError:
    print('An empty collection has no max value.')

print(max([], default = 0))
Output:
An empty collection has no max value.
0

If the key parameter is used to provide a function, the number return of that function is used to determine the maximum value in the collection. In the following example, the len() function is used to determine which string is the longest.

Example

Python
myList = ['small', 'bigger', 'very big']
print(max(myList, key = len))
Output:
very big