The max() function returns:
- the largest of two or more vales (such as numbers, strings, etc.)
- the largest item in an iterable (such as list, tuple etc.)
Syntax for two or more values
max(val1, val2, val... ,key)max() Parameters
Python max() function parameters:
| Parameter | Condition | Description |
|---|---|---|
val1,val2,val3... |
Required | Two or more values to compare |
key |
Optional | A function to specify the comparison criteria. Default value is None. |
max() Return Value
Python max() function returns the largest element.
Syntax for iterables
max(iterable, key, default)max() Parameters
Python max() function parameters:
| Parameter | Condition | Description |
|---|---|---|
iterable |
Required | Any iterable, with one or more items to compare |
key |
Optional | A function to specify the comparison criteria. Default value is None. |
default |
Optional | A value to return if the iterable is empty. Default value is False. |
max() Return Value
Python max() function returns the largest item in the iterable.
Examples
Example 1: Get the largest String with max() function
The max() function compares the strings lexicographically (i.e., it compares the strings character by character from left to right, alphabetically). The first string where a character is lexicographically greater than the corresponding character in the other string is returned as the maximum.
str1 = "Tutorial"
str2 = "Reference"
str3 = "for"
str4 = "you!"
max_val = max(str1, str2, str3, str4)
print(max_val) # Output: 'you!'output
you!Notice that the example returns you! because it is the string that comes last in lexicographical order among the provided strings
Another example:
str1 = "aaa"
str2 = "aaaa"
str3 = "AAA"
str4 = "AAAA"
max_val = max(str1, str2, str3, str4)
print(max_val) # Output: 'aaaa'output
aaaaExample 2: Get the largest string with max() function and key parameter
You can specify the comparison criteria by using the key parameter of the max() function.
For example, we can get the longest string by specifying the function len for the key parameter:
str1 = "Tutorial"
str2 = "Reference"
str3 = "for"
str4 = "you!"
max_val = max(str1, str2, str3, str4, key=len)
print(max_val) # Output: 'Reference'output
ReferenceExample 3: Get the maximum number of two or more values
If you specify two or more values, the largest value is returned.
x = max(10, 20, 30)
print(x) # Output: 30output
30Example 4: Get the maximum item in a List
For example, get the maximum number from a list of numbers:
number = [3, 2, 8, 5, 10, 6]
largest_number = max(number)
print(largest_number) # Output: 10output
10For example, get the largest string (ordered alphabetically) from a list of strings:
languages = ["Python", "Java", "JavaScript", "Rust"]
largest_string = max(languages)
print(largest_string) # Output: Rustoutput
RustExample 5: use max() function with dictionary
In the case of dictionaries, max() returns the largest key.
Let's use the key parameter in the max() function to find the dictionary key that is associated with the highest value.
square = {2: 4, -3: 9, -1: 1, -2: 4}
key1 = max(square)
print("The largest key:", key1) # Output: 2
key2 = max(square, key = lambda k: square[k])
print("The key with the largest value:", key2) # Output: -3
print("The largest value:", square[key2]) # Output: 9output
The largest key: 2
The key with the largest value: -3
The largest value: 9Observe that:
- The second
max()function use the lambda function passed to thekeyparameter.
Example 6: empty iterable and max() function
If the iterable is empty, a ValueError is raised.
my_list = []
x = max(my_list) # Triggers ValueError: max() arg is an empty sequence
print(x) output
Traceback (most recent call last):
File "main.py", line 2, in <module>
x = max(my_list) # Triggers ValueError: max() arg is an empty sequence
ValueError: max() arg is an empty sequenceTo avoid such exception, add default parameter. The default parameter specifies a value to return if the provided iterable is empty.
If the iterable is empty, a ValueError is raised.
my_list = []
x = max(my_list, default='0')
print(x) output
0Example 7: Find Maximum with Custom Function
You give a user-defined function as key parameter of max() function for making comparisons:
For example, find out who is the oldest student in the given list of students:
def myFunc(elem):
return elem[1] # return age
students = [('Ryan', 35), ('Tom', 25), ('Charlie', 30)]
oldest_one = max(students, key=myFunc)
print(oldest_one) # Output: ('Ryan', 35)output
('Ryan', 35)Example 8: Find Maximum with lambda
A key function may also be created with the lambda expression. It allows us to in-line function definition.
As in the example7, find out who is the oldest student in the given list of students:
def myFunc(elem):
return elem[1] # return age
students = [('Ryan', 35), ('Tom', 25), ('Charlie', 30)]
oldest_one = max(students, key=lambda student: student[1])
print(oldest_one) # Output: ('Ryan', 35)output
('Ryan', 35)Example 9: Find Maximum of Custom Objects
Now, let's create a list of students (as a custom object) and find out who is the oldest student.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return repr((self.name, self.age))
students = [Student('Ryan', 35), Student('Tom', 25), Student('Charlie', 30)]
oldest_one = max(students, key=lambda student: student.age)
print(oldest_one) # Output: ('Ryan', 35)output
('Ryan', 35)