Open In App

Use of min() and max() in Python

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: min() max() in Python 
Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments.
 

python3




l= ["ab", "abc", "abd", "b"]
 
l1="abc"
 
# prints 'b'
print(max(l))
 
# prints 'ab'
print(min(l))
 
#prints 'c'
print(max(l1))
 
#prints 'a'
print(min(l1))


Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. 
Parameters: 
By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters:
 

key – function that serves as a key for the min/max comparison 

 

Syntax: max(x1, x2, …, xn, key=function_name)
here x1, x2, x3.., xn passed arguments 
function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn. 
 

Return value: 
 

It returns a maximum or minimum of list according to the passed parameter.

 

Python3




# Python code explaining min() and max()
l = ["ab", "abc", "bc", "c"]
 
print(max(l, key = len))
print(min(l, key = len))


Output: 

abc
c

 

Explanation: 
In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length.
 

initially l = [“ab”, “abc”, “bc”, “c”] 
when we passed key=len as arguments then it works like 
l=[2,3,2,1] 

 

 

Python3




# Python code explaining min() and max()
def fun(element):
    return(len(element))
 
l =["ab", "abc", "bc", "c"]
print(max(l, key = fun))
 
# you can also write in this form
print(max(l, key = lambda element:len(element)))


Output: 

abc
abc

 

Another example: 
 

Python3




# Python code explaining min() and max()
l = [{'name':'ramu', 'score':90, 'age':24},
     {'name':'golu', 'score':70, 'age':19}]
 
# here anonymous function takes item as an argument.
print(max(l, key = lambda item:item.get('age')))


Output: 

{'age': 24, 'score': 90, 'name': 'ramu'}

 

Similar we can use min() function instead of max() function as per requirement.
 



Last Updated : 06 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads