Python max() Function [with Examples]

python programs

The max() function in Python returns the item that has the highest value.

  • It returns the largest value of two or more numbers passed as arguments.
  • It returns the lexicographically largest value if strings are passed as arguments.
  • It returns the largest item of the iterable such as list, set, tuple, etc.

max() Syntax and Parameters

The max() function, in general, has two types of syntaxes. We can pass multiple values separately or whole as an iterable as a single argument.

For individual values/objects, the one with the highest value is returned.

max(val1, val2, val3… ,key)
ParameterConditionDescription
val1, val2, val3…RequiredValues that need to be compared
keyOptionalA function specifying custom comparison criteria to find the maximum value.
The default value is None.

For iterable, the item with the largest value is returned.

max(iterable,key,default)
ParameterConditionDescription
iterableRequiredAny iterable, with one or more items to compare
keyOptionalA function specifying custom comparison criteria to find the maximum value.
The default value is None.
defaultOptionalA value to return if the iterable is empty.
The default value is False.

Examples using max()

Finding maximum when multiples values are passed as arguments.

>>> max('a', 'b', 'c')
c
>>> max(1, 2, 3, 4, 5)
5

Finding maximum when an iterable is passed as an argument.

>>> l= [1, 2, 3, 4, 5]
>>> max(l)
5
>>> l= ['a', 'b', 'c']
>>> max(l)
c

When we are not sure whether iterable has any value then it is better to provide default value to the max function to prevent the ValueError exception.

>>> l= []
>>> max(l, default=-1)
-1

Using len as key parameter to get the longest string as the max value.

>>> l= ['pencil', 'programmer']
>>> max(l, key=len)
programmer

We can also use user-defined lambda functions as key to get the desired value as the max result.

>>> brands = [('samsung', 4),
              ('Mi',3),
              ('Nokia', 5)]
>>> max(brands, key=lambda x: x[1])
('Nokia', 5)

Leave a Reply

Your email address will not be published. Required fields are marked *