Python max() Function


Python max() is a built-in function that returns the maximum value among the arguments supplied to the function. If an iterable is passed as the argument, the largest item in the iterable is returned.

python max() function

Python max() Syntax

max() for numbers

max (num1, num2, *args[, key])

Where,

  • num1 (required) – first object for comparison
  • num2 (required) – second object for comparison
  • *args (optional) – any object for the comparison
  • key (optional) – key function to which each argument is passed and the comparison is done based on the value returned by this function

There can be any number of objects supplied as arguments for comparison.

Jump directly to the example

max() for iterables

max(iterable, *[, key, default])

Where,

  • iterable – sequence or collection whose largest item is to be returned.
  • key (optional) – It is a function to which iterables are passed and the comparison is done based on the value returned by this function.
  • default (optional) – default value that specifies an object to return in case of empty iterable. If a default value is not given when empty iterable is passed, ValueError will be raised.

When an iterable is passed as the argument, the largest item of the iterable is returned. If multiple iterables are passed then, the list for which the key function return greater value is returned.

Jump directly to the example

Python max() Example

Example 1: Find maximum among the given numbers

>>> max(1,2,3,4)
4

>>> py_num = [3,5,7,9]
>>> max(py_num)
9

Example 1: Find number having maximum remainder when divided by 10 using key function

def findMax(num):
   rem = 0
   while(num):
     rem = num%10
     return rem

# using max(arg1, arg2, *args, key)
print('Number with max remainder is:', max(11,48,33,17,19, key=findMax))

# using max(iterable, key)
num = [11,48,33,17]
print('Number with max remainder is:', max(num, key=findMax))

When executed, this will yield following output.

Number with max remainder is: 19
Number with max remainder is: 48