Introduction to Max Function in Python
One of the frequently used built-in methods in Python is max(). The max() method returns the highest number among the function’s inputs when used to determine the maximum item of a given object. The biggest item in an iterable is returned if an iterable is used as the argument value. Syntax:
The max() method is essentially implemented in two distinct ways in
python.
max(num1, num2, *args[,key])
-
num1:
required parameter, the first object for comparison -
num2:
required parameter, a second object for comparison -
*args:
optional parameters, any object for comparison -
Key:
optional parameter, it will hold the function (can be built-in or user-defined), and comparison will be done
based on the return value
of this key function.
max(iterable, *[,key,default])
-
iterable (required):
an iterable object like list, tuple, dictionary, string, etc. -
key (optional):
key function to customize the sort order. Max value will be returned on the basis of the return value of this applied function -
default (optional):
the default value to be returned when the iterable is empty
Examples of Max Function in Python
The code examples following will assist in comprehending how the max ()
function.
Example #1
Python iterable is used in a programme to demonstrate the capability of max(). Code:
# Program to illustrate max() functionality
Results:
# example 1: Input --> basic integers
print("input --> 1, 9, 72, 81, 28, 49, 90, 102, 150, 190")
print("max: ", max(1, 9, 72, 81, 28, 49, 90, 102, 150, 190))
# Input --> a string
print("input -->'aCDeFQwN'")
print("max: ", max('aCDeFQwN'))
# Input --> list
inp1 = [19, 40, 228, 112, 90, 506, 810, 119, 202]
print("input -->", inp1)
print("max: ", max(inp1))
# Input --> tuple
inp2 = (91, 40, 822, 112, 90, 506, 108, 119, 202)
print("input -->", inp2)
print("max: ", max(inp2))
# Input --> dictionary
inp3 = {
'John': [10, 20, 30],
'Rob': [12, 18, 36],
'Karen': [10, 15, 19]
}
print("input -->", inp3)
print("max among dict keys: ", max(inp3.keys()))
print("max among dict values: ", max(inp3.values()))
Code – Explanation:
- The first call of max() à parameters includes basic integers, and the max value is returned among these integers.
- The second call of max() à parameter is a string that includes both lower and upper case characters. Max value is returned as per ASCII value.
-
The third call of max() à parameter is a
list
of integers; the max value is returned among this list of values. - The fourth call of max() à parameter is a tuple of integers; the max value is returned among this tuple.
-
The fifth call of max() à parameter is a
dictionary
, max value from dictionary keys and dictionary values are printed.
Notice that max() will generate an error if all of the arguments are not of the same type.
# Input type should be of same type, otherwise it will raise an error
print(max('a', 12, 18, 90, 'q', 29, 'b', 'd', 63))
Example #2
Example of the max() function using the provided key function Code:
#Program to illustrate max() functionality, when key is set to some function
Produces:
# Input --> list of strings
inp = ['John', 'Rob', 'Karen', 'Diana', 'Emanual', 'Alexnder', 'Tina']
print("input -->", inp)
def length(item):
return len(item)
# Key function --> len()
print("Using user defined function")
print("max: ", max(inp, key = length))
# This can be implemented using built-in function len()
print("Using built-in function")
print("max: ", max(inp, key = len))
# Using lambda function
print("Using lambda function")
print("max: ", max(inp, key = lambda item : len(item)))
# Input --> multiple iterables
x = [10, 20, 30]
y = [5, 10, 15, 20, 25]
print("max among x and y :", max(x, y, key = len))
print("max among x and y :", max(x, y))
Code Explanation:
- The input list is defined, which consists of different names (string type).
- First, max() is called with user-defined function; this will return the string value from the given input list, which has a maximum number of characters. In this example, “Alexnder” will be printed as len(Alexnder) is greater than all other names in the list.
- Second max() function takes built-in function len() as its key function argument.
-
The third max() call is implemented using a lambda function.
In all the examples, we got the same output. Only the way for defining function is changed. -
The last max() call takes multiple iterables (lists).
When key=len à list with max number of items will be the output
When the key is not set to any function à lists will be compared element-wise, as shown in the output above.
Example #3
The maximum digit sum list value may be returned by a programme. Code:
"""
Produces:
Python max Function Example
key function : sum of digits of the list items
"""
def sum_digits(num):
sum = 0
while(num > 0):
rem = num % 10
sum = sum + rem
num = num // 10
return sum
# Input --> list of positive integers
inp = [120, 20, 42, 212, 802, 139, 175, 802, 468]
print("Input List = ", inp)
print("Maximum Value in the List = ", max(inp, key = sum_digits))
Code Explanation:
- A function “sum_digits” is defined, which takes a number and returns its sum of digits.
- The input list which contains positive integers is created.
- max() is called with key function: sum_digits. This will return the list item, which has a max sum of digits.
Notice that max() will throw an error if iterable is empty. The “default” parameter is used to deal with this problem.
inp = []
print("input:", inp)
print(max(inp))
By offering the default solution, the aforementioned problem may be resolved.
parameter:
inp = []
print("input:", inp)
print(max(inp, default=0))