Python max() Builtin Function

Python max()

Python max() function is used to find the maximum of a given iterable or, two or more arguments.

We can provide either an iterable; or two or more items as arguments to max() function, but not mix iterable and the other items.

Optionally, we can also give a named key function, based on whose return value the items in the iterable or the arguments are compared and the maximum is found.

Syntax – max()

The syntax of max() function is

max(iterable, *[, key, default])
# or
max(arg1, arg2, *args[, key])

We can also provide a default value, which will be returned if there are no items in the iterable.

Example 1: Find Maximum of Iterable

In this example, we will take a list of numbers and find the largest number in the list using max() function.

Python Program

a = [18, 52, 23, 41, 32]
largest = max(a)
print(f'Largest number in the list is : {largest}.')
Run

Output

rgest number in the list is : 52.

Example 2: Find Maximum of Two or More Items

In this example, we will take five numbers and find the largest number of these using max() function.

Python Program

largest = max(18, 52, 23, 41, 32)
print(f'Largest number in the list is : {largest}.')
Run

Output

Largest number in the list is : 52.

Example 3: max() with key function

In this example, we will take a list of numbers and find the number which leaves largest reminder when divided with 10, using max() function.

We will define a lambda function for key parameter that returns the reminder of the element in the list for comparison.

Python Program

a = [18, 52, 23, 41, 32]
keyfunc = lambda x: x % 10
largest = max(a, key=keyfunc)
print(f'Number that leaves largest reminder is : {largest}.')
Run

Output

Number that leaves largest reminder is : 18.

Example 4: max() with default value

In this example, we will take an empty list and find the maximum number of the list using max() function. Since the list is empty, if we set default parameter for the max() function, the default value is returned.

Python Program

a = []
largest = max(a, default = 99)
print(f'Largest number in the list is : {largest}.')
Run

Output

Largest number in the list is : 99.

Summary

In this tutorial of Python Examples, we learned the syntax of max() builtin function and how to use it, with the help of examples.