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.
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 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.
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() Function Example 4
This simple example just finds the maximum value in a series of numbers passed to the function.
Python max() Function Example 5
Using the max() function on a dictionary returns the largest key of the 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() 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.
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.
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.