Skip to content
Related Articles
Open in App
Not now

Related Articles

Use of min() and max() in Python

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 06 Jun, 2021
Improve Article
Save Article

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.


l= ["ab", "abc", "abd", "b"]
# prints 'b'
# prints 'ab'
#prints 'c'
#prints 'a'

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. 
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.



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




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 




# Python code explaining min() and max()
def fun(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)))




Another example: 


# 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')))


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


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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!