What is Python's max() function
Posted in Python by Dirk - last update: Feb 09, 2024
max()
is a Python built-in function that returns the maximum value from a sequence, such as a list, tuple, or string. It can also handle multiple iterables, apply a custom key function, and provide a default value for empty sequences.
There are different forms of the max() function, each serving a specific purpose.
Basic Usage
The max()
function takes an iterable (e.g., a list, tuple, or string) as its first argument and returns the maximum element.
Syntax: max(iterable, \*iterables, key=default, default=None)
with:
-
iterable
: This is the required argument representing the sequence (e.g., list, tuple, or string) from which the maximum value is to be determined.
-
*iterables
This allows for multiple iterables to be passed as additional arguments. It compares elements from all the iterables and returns the maximum.
-
key
: An optional argument specifying a custom function that determines the comparison key. It is applied to each element before comparison.
-
default
: Another optional argument specifying a default value to be returned if the iterable is empty. If not provided, it defaults to None
.
A simple example:
numbers = [3, 7, 1, 9, 4]
max_number = max(numbers)
print('Max. number:',max_number)
Result:
Note: When you compare different types of objects in Python, such as integers with strings or floats with strings, you might encounter a TypeError
. Python doesn’t allow direct comparisons between different data types. To make meaningful comparisons, you may need to convert one or both of the operands to a common type
Multiple arguments
The max()
function in Python can take multiple arguments without requiring them to be wrapped in a list or another iterable. You can provide multiple individual values as arguments, and the function will return the maximum value among them. Here’s an example:
max_value = max(5, 8, 2, 10)
print(max_value) # Output: 10
In this example, the max()
function is used with individual values (5, 8, 2, and 10), and it returns the maximum value, which is 10.
Multiple Iterables
You can compare elements from multiple iterables by passing them as separate arguments.
list1 = [1, 5, 3]
list2 = [8, 2, 6]
max_value = max(list1, list2)
print(max_value) # Output: [8, 2, 6]
In the expression max(list1, list2)
, the max()
function will compare the lists lexicographically (~alphabetically). The list that comes later in lexicographical order will be considered the maximum.
Comparing [1, 5, 3]
and [8, 2, 6]
element-wise, the first elements are 1 and 8. Since 8 is greater than 1, list2
is considered greater in lexicographic order.
Therefore, the result of max(list1, list2) will be
[8, 2, 6]. The function considers the maximum list based on the lexicographical comparison of their elements.
If you want to have the maximum of value in the two lists - you have to do it differently.
list1 = [1, 5, 3]
list2 = [8, 2, 6]
max_value = max(max(list1), max(list2))
print("Maximum value:", max_value)
In this example, max(list1)
and max(list2)
are used to find the maximum values in each individual list, and then the outer max()
is used to find the maximum value between these two maximum values. The final result will be the highest value present in either of the two lists.
Or you can use the unpacking *
operator (the unpacking operator ‘unpacks’ the values from iterable objects in Python into individual values)
list1 = [1, 5, 3]
list2 = [8, 2, 6]
max_value = max(*list1, *list2)
print("Maximum value:", max_value)
The *
(unpacking) operator is used to provide the elements of the lists as separate arguments to the max()
function.
Output
Custom Key Function
The key
parameter allows you to specify a custom function to determine the comparison key.
words = ["apple", "banana", "orange", "kiwi"]
max_length_word = max(words, key=len)
print(max_length_word) # Output: banana
Custom keys can also be used for dictionaries: in example below , the goal is to find the person with highest age specified by the “age” key in the dictionary
dictionaries = [{"name": "John", "age": 30},
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 35}]
max_age_person = max(dictionaries, key=lambda x: x["age"])
print(max_age_person) # Output: {'name': 'Bob', 'age': 35}
The max()
function is used with the key
parameter, which takes a function (in this case, a lambda function) to determine the comparison key. The lambda function lambda x: x["age"]
extracts the “age” value from each dictionary.
The max()
function then compares the dictionaries based on the values returned by the key function.
Output:
{'name': 'Bob', 'age': 35}
List of strings
When using the max()
function with a list of strings, it determines the maximum value based on alphabetical order
strings = ["apple", "banana", "orange", "kiwi"]
max_string = max(strings)
print(max_string) # Output: orange
Here’s how the comparison works in the example:
- “apple” comes before “banana” (the first characters ‘a’ vs. ‘b’).
- “banana” comes before “orange” (the first characters ‘b’ vs. ‘o’).
- “orange” comes before “kiwi” (the first characters ‘o’ vs. ‘k’).
Therefore, the maximum string in alphabetical order is “orange”. If all strings have the same starting characters, the function compares the next characters until a difference is found.
Keep in mind that this lexicographical comparison might not always correspond to what you would consider the “maximum” string in a real-world context. If you need a custom comparison, you can use the key
parameter to specify a function that defines the comparison criteria.
Default value
You can provide a default value using the default parameter. If the iterable is empty, the default value will be returned.
empty_list = []
max_value = max(empty_list, default="No elements in the list")
print(max_value) # Output: No elements in the list
Other articles