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.
l= ["ab", "abc", "abd", "b"] # prints 'a' print(max(l)) # prints 'ab' print(min(l)) |
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.
# Python code explaning min() and max() l = ["ab", "abc", "bc", "c"] print(max(l, key = len)) print(min(l, key = len)) |
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.
# 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))) |
abc abc
Anoter example:
# 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'))) |
{'age': 24, 'score': 90, 'name': 'ramu'}
Similar we can use min() function instead of max() function as per requirement.
Recommended Posts:
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- Python vs PHP
- pow() in Python
- SHA in Python
- gcd() in Python
- Any & All in Python
- SQL using Python | Set 1
- chr() in Python
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.



