Python max() Method

The max() method returns the largest value from the specified iterable or multiple arguments.

Syntax:

max(iterable, key, default)
max(arg1, arg2, *args, key)

Parameters:

  1. iterable: An iterable (list, tuple, set, dict, string).
  2. key: (Optional) The built-in or user-defined function to be used for comparison.
  3. default: (Optional) The value to be returned if the iterable is empty.

Return Value:

Returns the largest value.

The following example returns the largest value from the given list.

Example: Largest Value in List
nums = [1, 7, 8, 5, 4, 6, 2, 3]
largest = max(nums)
print("The largets number is: ", largest)
Output
The largets number is:  8

The max() method can also be used with strings.

Example: Largest Value in String List
lst = ['abc','def','ghi']
largest = max(lst)
print("The largest string is: ", largest)
Output
The largest string is: ghi

In the above example, the largest string based on the alphabetical order is returned.

In the case of strings, the highest value can also be returned based on other parameters like the length of the string if the key parameter is used.

Example: max()
cities = ['Mumbai','New York','Paris','London']
largest = max(cities, key=len)
print("The largest string based on length is: ", largest)
Output
The largest string based on length is:  New York

You can pass multiple iterables, as shown below.

Example: max()
cities = ['Mumbai','New York','Paris','London']
favcities = ['Pune', 'New York', 'Johannesburg']

largest = max(cities, favcities, key=len)
print("The largest list is: ", largest)
Output
The largest list it: ['Mumber', 'New York', 'Paris', 'London']

In the above example, the max() method will return a list with more elements, which is cities list because it contains four elements.

The max() method can also be used in dictionaries to return the largest key.

Example: max()
numdict = {1:'One', 2:'Two', 5:'Five', 0:'Zero', 4:'Four', 3:'Three'}
largest = max(numdict)
print("The highest key value is: ", largest)
Output
The highest key value is:  5

If the specified iterable is empty, then it will throw ValueError. Use the default parameter if you are not sure whether the specified iterable is empty or not.

Example: max()
cities = []

largest = max(cities, key=len, default='No elements')
print("The largest city is: ", largest)
Output
The largest city is: No elements

The max() method can also work without any iterable as arguments. If multiple arguments are passed, it will return the argument with maximum value.

Example: max()
largest = max(1, 7, 8, 5, 4, 6, 2, 3)
print("The highest number is: ", largest)

largest = max('Mumbai','New York','Paris','London', key=len)
print("The largets string is: ", largest)
Output
The highest number is:  8
The largets string is: New York
Want to check how much you know Python?