Python max() Function

Click to share! ⬇️

Python max() Function

Another built-in Python function that is useful when analyzing data is max(). It works in a similar way to min() which we just covered, but in reverse so to speak. Instead of finding the smallest item, it finds the largest item. Just like min(), it accepts either a sequence as input or a series of two or more items as the inputs. When given a sequence, max() returns the largest item in the sequence. When a series of two or more items are provided, max() returns the largest item among them. Let’s look at several examples of how max() works in Python now.

Python max() Function Example 1

Just like we did with the min() function, we can first initialize a list of numbers to work with.

list of numbers

Now to find the biggest item in the list, we can call the max() function and pass in the variable which holds the list of numbers. The max() function correctly finds the integer 99 as the largest within the list of numbers.

python max function integers

Python max() Function Example 2

The max() function works with Tuples just like it does with lists. This example here is a Tuple containing all of the same numbers. The max() function again reports back that the integer of 99 is the largest value in the Tuple.

max function on tuple

Python max() Function Example 3

Here is a list of floating-point numbers we can call the max() function on. Out of all the floating-point values, max() finds 105.8 as the largest.

python max() floats

Python max() Function Example 4

This simple example just finds the maximum value in a series of numbers passed to the function.

max series of numbers

Python max() Function Example 5

Using the max() function on a dictionary returns the largest key of the dictionary.

python max dictionary

Python max() Function Example 6

If the keys of a dictionary are strings, the max() function returns the largest string according to alphabetical order.

python max() dict string

Python max() Function Example 7

You should not call max() on an empty list. If you do an exception will be thrown. To get around this, you can pass a default value to be used if the list is empty.

max() empty list

Python max() Function Example 8

A custom key can be defined to determine how max() works. This example shows the default algorithm for finding the max of a string(alphabetical) and using a custom key to change this to using ASCII length to find the largest value.

max key

Python max() Function Summary

The Python max() function returns the item with the highest value or the item with the highest value in an iterable. If the values are strings, an alphabetical comparison is done. The syntax for multiple items is max(n1, n2, n3, …) or max(iterable) in the case of an iterable.

Click to share! ⬇️