Tutorial Study Image

Python max()

The built-in function max() helps to  returns the largest element in a given iterable. It can also possible to find the largest element between two or more parameters.

# to find the largest item in an iterable
max(iterable, *iterables, key, default)

# to find the largest item between two or more objects
max(arg1, arg2, *args, key)

max() Parameters:

max() function with iterable has the following parameters.

max(iterable, *iterables, key, default)

Parameter Description Required / Optional
iterable  an iterable such as list, tuple, set, dictionary, etc. Required
*iterables any number of iterables; can be more than one Optional
key a key function where the iterables are passed and comparison is performed Optional
default  default value if the given iterable is empty Optional


max() function without iterable() have following parameters.

max(arg1, arg2, *args, key)

Parameter Description Required / Optional
arg1 an object; can be numbers, strings, etc Required
arg2 an object; can be numbers, strings, etc Required
*args any number of objects Optional
key  a key function where each argument is passed and comparison is performed Optional

max() Return Value

In case of passing an empty iterator, it will raise a ValueError exception for avoiding this, we can pass the default parameter.
And if we passing more than one iterators, then the largest item from the given iterators is returned.

Input Return Value
Integer largest integer
String the character with maximum Unicode value

Examples of max() method in Python

Example 1: Get the largest item in a list

number = [13, 2, 8, 5, 10, 26]
largest_number = max(number);

print("The largest number is:", largest_number)


The largest number is: 26

Example 2: Find the largest string in a list

languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);

print("The largest string is:", largest_string)


The largest string is: Python

Example 3:Find the max() in dictionaries

square = {2: 4, -3: 9, -1: 1, -2: 4}

# the largest key
key1 = max(square)
print("The largest key:", key1)    # 2

# the key whose value is the largest
key2 = max(square, key = lambda k: square[k])

print("The key with the largest value:", key2)    # -3

# getting the largest value
print("The largest value:", square[key2])    # 9


The largest key: 2
The key with the largest value: -3
The largest value: 9

Example 4:Find the maximum among the given numbers

result = max(4, -5, 23, 5)
print("The maximum number is:", result)


The maximum number is: 23

Example 5:Find the max() of objects

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[%s]' % self.id

def get_data_id(data):
    return data.id

# max() with objects and key argument
list_objects = [Data(1), Data(2), Data(-10)]

print(max(list_objects, key=get_data_id))