This article will go through the Python max Function and it’s uses complete with several examples.

The Python max function is used to find the ‘max’ value of a specific sequence or iteratable. By changing it’s parameters we can even change how this max value is calculated.

You might to have an ASCII table open with you while using this function. Here’s a link to one.


Syntax

max(sequence, default = "", key = func)
  • Sequence is the sequence of numbers/values through which the max function will be going through. Example; x = [5,6,7,8,3]
  • default holds the default value that will be printed if the sequence of values is empty. (Optional)
  • The key parameter can be assigned a function to change the way the max function calculates the max value. More on this below. (Optional)

Example 1:
>>> x = [5,7,8,2,5]
>>> max(x)
8

>>> x = []
>>> max(x, default = 'empty')
'empty'

When comparing between strings, the max function by default, returns the one with the highest ASCII value. In comparing values in a dictionary, the max function returns the key with the highest value. Also, when you pass a single string through the max function, it will treat each individual character as a string of length 1, returning the highest value string.

Example 2:
>>> max('a','A')
'a'

>>> x = { 1: "Cat", 2: "Dog", 3: "Fox"}
>>> max(x)
3

>>> max("Hello")
'o'

Key Parameter

By changing the key value to the str.lower function, the max function will ignore any capitalization and treat all the strings like lowercase.

>>> max('a', 'b', 'D')
'b'

>>> max('a', 'b', 'D', key = str.lower)
'D'

By changing the key value to the len function, the max function will return the string which has the greatest length, instead of judging by ASCII standards.

>>> x = ["Apple", "Orange", "Automobile"]
>>> max(x)
'Orange'

>>> max(x, key = len)
'Automobile'

This marks the end of the Python max Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

You might also want to see the min function which is the exact opposite to the max function.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments