↓ Skip to main content

The max Function in Python

·777 words·4 mins·
 Author
Author
Francisco Bustamante
Chemist, data scientist and Python programmer.
Table of Contents

You may find it strange to have a whole post just for max. That is because its most common use is simply finding the highest number in a set of numbers. For example:

list_1_to_5 = [2, 1, 4, 5, 3]
max(list_1_to_5)
5

But there are other uses, which we will see throughout this article.

More than one iterable
#

The function can receive more than one iterable. For example, two lists:

list_1_to_5 = [2, 1, 4, 5, 3]
list_1_to_3 = [2, 3, 1]
max(list_1_to_3, list_1_to_5)
[2, 3, 1]

Can you make sense of the result? The function compares the two lists item by item. The first item is the same in both lists. The second item is different, so the list with the larger second item was returned.

The key parameter
#

The real power of the max function is the key parameter. This parameter can receive a function that changes the condition for what is considered the maximum.

Using the len function to return the longest list:

max(list_1_to_3, list_1_to_5, key=len)
[2, 1, 4, 5, 3]

Using the sum function to return the list with the largest sum of its items:

max(list_1_to_3, list_1_to_5, key=sum)
[2, 1, 4, 5, 3]

What if there are repeated items? Using the default max function, the largest value is returned, as expected:

list_with_repeats = [1, 1, 2, 3, 4, 5, 6, 6, 2, 2]
max(list_with_repeats)
6

But we can use methods such as a list’s count, which returns the number of occurrences of each item in the list. The number that appears most often in the list will be returned:

max(list_with_repeats, key=list_with_repeats.count)
2

Combining with itertools and operator
#

But what if you actually want the largest value among the two lists we created? You can join them and ask for the maximum value of the union. We can use the chain function from itertools, which is part of a standard Python installation:

from itertools import chain
max(chain(list_1_to_3, list_1_to_5))
5

We have already seen that when there is more than one iterable, the default is to return the one with the largest first item. If those are all equal, the one with the largest second item, and so on:

list_of_tuples = [(1, 2, 3), (3, 1, 1), (8, 3, 3), (3, 4, 2)]
max(list_of_tuples)
(8, 3, 3)

But what if we want to start from the largest second item? Or third? We can use itemgetter from operator, which is part of a standard Python installation:

from operator import itemgetter
max(list_of_tuples, key=itemgetter(1))
(3, 4, 2)
max(list_of_tuples, key=itemgetter(2))
(1, 2, 3)

Remember: in Python, counting starts at zero :-)

Working with dictionaries
#

What happens if a dictionary is passed? By default, it returns the largest key of the dictionary. In the example, the keys are strings, so it returns the string with the largest first letter (position in the alphabet):

elements = {'zinc': 30,
            'gold': 79,
            'calcium': 20,
            'hydrogen': 1,
            'lead': 82, }

max(elements)
'zinc'

If we want the criterion to be the largest value instead of the largest key, we can use the dictionary’s get method:

max(elements, key=elements.get)
'lead'

Notice that the key with the largest associated value was returned. It is more useful to return the (key, value) pair. We can use an anonymous lambda function for that.

Returning the (key, value) pair with the largest key:

max(elements.items(), key=lambda k: k[0])
('zinc', 30)

Returning the (key, value) pair with the largest value:

max(elements.items(), key=lambda k: k[1])
('lead', 82)

Working with numbers in string form
#

To finish, we have already seen that with strings the largest positional value is returned:

strings = ['1', '100', '111', '2']
max(strings)
'2'

The result was ‘2’ because it is the largest value when comparing the first positions of each string. But if we want the largest integer, we just use the int function as the key:

max(strings, key=int)
'111'

Conclusion
#

Did you know about all these possible uses of the max function? If we missed an interesting use, let us know in the comments.

The key parameter is a classic example of why it is important to read the documentation when you use a function for the first time. We end up discovering more features than the one that shows up most obviously on first use.

Oh, and everything shown in this post applies in the same way to the min function ;-)

Did you like this article? It is part of the programming Drops, a set of shorter posts focused on fundamentals, covering some aspects of the Python language and of programming in general. You can read more of these articles by browsing the "drops" tag here on the site.

Until next time!

Related