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:
- iterable: An iterable (list, tuple, set, dict, string).
- key: (Optional) The built-in or user-defined function to be used for comparison.
- 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.
nums = [1, 7, 8, 5, 4, 6, 2, 3]
largest = max(nums)
print("The largets number is: ", largest)
The largets number is: 8
The max()
method can also be used with strings.
lst = ['abc','def','ghi']
largest = max(lst)
print("The largest string is: ", largest)
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.
cities = ['Mumbai','New York','Paris','London']
largest = max(cities, key=len)
print("The largest string based on length is: ", largest)
The largest string based on length is: New York
You can pass multiple iterables, as shown below.
cities = ['Mumbai','New York','Paris','London']
favcities = ['Pune', 'New York', 'Johannesburg']
largest = max(cities, favcities, key=len)
print("The largest list is: ", largest)
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.
numdict = {1:'One', 2:'Two', 5:'Five', 0:'Zero', 4:'Four', 3:'Three'}
largest = max(numdict)
print("The highest key value is: ", largest)
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.
cities = []
largest = max(cities, key=len, default='No elements')
print("The largest city is: ", largest)
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.
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)
The highest number is: 8
The largets string is: New York