Python max() Function



The Python max() function is used to retrieve the largest element from the specified iterable.

Finding the maximum of two given numbers is one of the usual calculations we perform. In general max is an operation where we find the largest value among the given values. For example, from the values “10, 20, 75, 93” the maximum value is 93.

Syntax

Following is the syntax of Python max() function −

max(x, y, z, ....)

Parameters

  • x, y, z − This is a numeric expression.

Return Value

This function returns largest of its arguments.

Example

The following example shows the usage of the Python max() function. Here we are retrieving the largest number of the arguments passed to the function.

print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))

When we run above program, it produces following result −

max(80, 100, 1000) :  1000
max(-20, 100, 400) :  400
max(-80, -20, -10) :  -10
max(0, 100, -400) :  100

Example

In here, we are creating a list. Then the largest element of the list is retrieved using max() function.

# Creating a list
List = [74,587,24,92,4,2,7,46]
res = max(List)
print("The largest number in the list is: ", res)

While executing the above code we get the following output −

The largest number in the list is:  587

Example

In the example below, a list of equal length of strings is created. Then the largest string is retrieved based on the alphabetical order:

# Creating the string
Str = ['dog','cat','kit']
large = max(Str)
print("The maximum of the strings is: ", large)

Output of the above code is as follows −

The maximum of the strings is:  kit

Example

We can also use the max() function in the dictionary for finding the largest key as shown below:

# Creating the dictionary
dict_1 = {'Animal':'Lion', 'Kingdom':'Animalia', 'Order':'Carnivora'}
large = max(dict_1)
print("The largest key value is: ", large)

Following is an output of the above code −

The largest key value is:  Order
python_built_in_functions.htm
Advertisements