Use of min() and max() in Python

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 passed in its argument and lexicographically largest value and lexicographically smallest value respectively, if strings are passed as arguments.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Here you notice that output comes according to lexicographical order. So we can find output according to length of string or the requirement by simply passing functon name or lambda expression.



Syntax: max(x1, x2, ..., xn, key=function_name)

here x1, x2, x3.., xn passed arguments
function_name : denotes which type of operaton you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

abc
c

Expanation:
In the above program, max function takes two arguments l(list) and key = len(function_name). len function returns length of elements of the list, then length of each element of the list is compared with another element and store the maximum length of the element. Finally returns that element which has maximum length.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code explaning 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)))

chevron_right


Output:

abc
abc

Anoter example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code explaning 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')))

chevron_right


Output:

{'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

Coder and Django developer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.