Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Python’s max function

The max() function in Python is one of the easiest to learn and use. It is also very versatile. It takes any type of iterable (e.g., a list) as input and returns the maximum value in that iterable.

Let us first try using this function with a list as input.

Python max with list iterable

Consider for instance:

mylist = [2,347,5,15,1,67]
print (max(mylist))

This outputs, as expected:

347

Let us try it with a list of strings:

mylist = ["Humpty", "Dumpty", "sat", "on", "a", "wall"]
print (max(mylist))

The output is:

wall

The reason wall is printed is because by default, max on a list of strings returns the string that has the lexicographically highest value. In other words, sort the strings by the lexicographic order and pick the string that is at the end. Let us try:

mylist = ["America", "Russia", "China"]
print (max(mylist))

This gives:

Russia

Python max with string

Because max takes an iterable as input, a string is a valid input. Let us try:

mylist = "Kodeclik"
print (max(mylist))

We get:

o

This is because the individual characters of the string, when sorted, are organized into “K”, “c:, “d”, and so on with “o” being the lexicographically last character.

Python max with list iterable and custom sorting function

You are not restricted to using Python defaults for sorting. We can specify a different comparison operator to use with the max() function. For instance, in the earlier example of sorting the elements of a list, we can use length of the element as the criterion to sort the elements:

mylist = ["Humpty", "Dumpty", "sat", "on", "a", "wall"]
print (max(mylist,key=len))

The output is:

Humpty

Recall that earlier the result of this max() function was “wall”. Now it is “Humpty” because we are seeking the (string) element that has the longest length.

Python max with individual objects

Python max function

We can also pass to max, not an iterable, but individual objects. For instance:

print (max(2,3,4,10))

This gives as output:

10

We can mix integers and floats in the input:

​​print (max(2,31.3,4,10))

This gives as output:

31.3

On the other hand, if you try:

print (max(2,31.3,4,10,"hello"))

We get:

Traceback (most recent call last):
 File "main.py", line 1, in <module>
  print (max(2,31.3,4,10,"hello"))
TypeError: '>' not supported between instances of 'str' and 'float'

This is because the comparison operator does not know to compare an integer against a string. (But it works when you mix integers and floats).

Just as we customized how elements are sorted, we can do the same when passing individual objects:

print (max("Humpty","hello",key=len))
print (max("Humpty","hello"))

This outputs:

Humpty
hello

In the first line, we are arranging the elements by length and thus “Humpty” is returned. In the second line, there is no “key” variable specified and as a result the default is lexicographic ordering and thus the max value returned is “hello”.

Python max with a dictionary

Let us create a dictionary and apply the max() function on it:

months = {1: "January",
          2: "February",
          3: "March",
          4: "April",
          5: "May",
          6: "June",
          7: "July",
          8: "August",
          9: "September",
          10: "October",
          11: "November",
          12: "December"}

print(max(months))

This outputs:

12

Thus we can see that by default, max() applied to a dictionary uses the key values to sort. If we wish to sort not by the keys but by the associated values, we can define a key parameter and pass on a function to it. Let us suppose we want to sort by the value of the (month) strings so that the max() function should return “September” since the month starting with “S” is the lexicographically largest. If we try:

print(max(months, key=len))

we will get the error:

Traceback (most recent call last):
 File "main.py", line 14, in <module>
  print(max(months, key=len))
TypeError: object of type 'int' has no len()

This is because by default the function specified in key is being applied to the dictionary’s keys, not to the dictionary’s values. We can fix this problem by defining a lambda function:

print(max(months, key= lambda k: months[k]))

This gives, as expected:

9

because the month with key=9 has the value “September”. To find the actual month, we can do:

monthkey = max(months, key= lambda k: months[k])
print(months[monthkey])

This will output:

September

Instead of sorting the dictionary’s values lexicographically, we can try to sort it by the length of the string.

monthkey = max(months, key= lambda k: len(months[k]))
print(months[monthkey])

This outputs:

September

How come? This is because “September” is also the string with the largest number of characters, in addition to being the string that begins with lexicographically largest value. To confirm that this lambda function is working as intended, let us artificially change a month’s name:

months = {1: "January",
          2: "February, the second month",
          3: "March",
          4: "April",
          5: "May",
          6: "June",
          7: "July",
          8: "August",
          9: "September",
          10: "October",
          11: "November",
          12: "December"}

monthkey = max(months, key= lambda k: len(months[k]))
print(months[monthkey])

This will now output:

February, the second month

confirming that the function is working as intended.

As you have learnt in this blogpost, the max() function in Python is a very versatile function, applicable both to individual values as well as to values in an iterable. Furthermore, you can customize the default behavior of the max() function by providing your own way to rank order the input values.

If you liked the Python max() function, checkout our blogpost on the Python min() function.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.