max() Builtin Function


Python max()

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

In this tutorial, you will learn the syntax of max() function, and then its usage with the help of example programs.

Syntax of max()

The syntax of max() function is

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

where

ParameterDescription
iterableAn iterable like list, tuple, etc.
arg1, arg2, ...Values in which we have to find the maximum.
defaultA default value, which will be returned if there are no items in the iterable.
key[Optional] A key function based on whose return value the items in the iterable or the arguments are compared and the maximum is found.

Examples

1. Find maximum value in 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}.')

Output

rgest number in the list is : 52.

2. Find maximum of two or more numbers

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}.')

Output

Largest number in the list is : 52.

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}.')

Output

Number that leaves largest reminder is : 18.

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}.')

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.