Updated March 28, 2023
Introduction to Max Function in Python
Python max() is one of the common built-in functions. max() function is used to find the maximum item of a given object, i.e. it returns the maximum value among the function’s arguments. If an iterable is passed as the argument value, the largest item in the iterable is returned.
Syntax:
Basically, there are two different ways of implementing the max() function 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 below code snippets will help in understanding the functionality of the max() function.
Example #1
Program to illustrate max() functionality using python iterable.
Code:
# Program to illustrate max() functionality
# 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()))
Output:
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.
# 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
Illustration of max() function with given key function
Code:
#Program to illustrate max() functionality, when key is set to some function
# 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))
Output:
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
Program to return list value with the max sum of digits.
Code:
"""
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))
Output:
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.
inp = []
print("input:", inp)
print(max(inp))
The above error can be handled by providing the default parameter:
inp = []
print("input:", inp)
print(max(inp, default=0))
Recommended Articles
This is a guide to Max Function in Python. Here we discuss the Introduction and two different ways of implementing max() function in python and different examples and its code implementation. You may also look at the following articles to learn more –