The max()
function returns the largest item in an iterable or the largest of two or more positional arguments.
max(iterable, *args, key = None, default = None)
iterable | An iterable object such as a list, tuple, set, etc containing the elements to be compared. It is only necessary if the elements are not given as positional arguments. |
args | Arbitrary more than two values given as positional arguments. It is only necessary if the elements to be compared are not given as an iterable. |
key | A callable object such as a function or a lambda function to be used as the comparison criteria |
default | A default value that will be returned in case the iterable is empty. It is only relevant if the elements are in an iterable and not as positional arguments. |
Note The iterable
argument and the *args
arguments are exclusive. If one is given the other one is omitted.
The function returns the largest item in the iterable or the largest of the given positional arguments.
Due to in-comparability of some data types, the max()
function ( as well as other related functions such as min() and sorting functions such as sorted()), is only used with items of homogenous or closely related types. For example; while we can tell which is greater between 1(int) and 1.5(float), it would be impossible to tell logically what is larger between a number and a string e.g 'a' and 1, passing such kind of items to the max()
function will raise a TypeError
.
The optional keyword argument, default, is used to specify a default value which will be returned in case the iterable is empty. If the default value is not specified, a ValueError
is raised.
The optional keyword argument, key, specifies the function which will be used as the comparison criteria. The function specified as the key gets applied to all the items and the resulting values are used for comparison instead of the elements themselves. For example if we want to get the list with the largest number of items in a two dimensional list, we can pass the len
function as the key, and the lists will be compared based on their lengths.
The lambda functions are commonly used to create inline keys for the max()
and related functions.