+

Using min () and max () in Python

Let`s take a look at some interesting facts about the min () and max () functions. These functions are used to calculate the maximum and minimum values ​​passed in its argument, and the lexicographically largest value and lexicographically smallest value, respectively, if strings are passed as arguments.

l = [ "ab" , "abc" , "abd" , "b" ]

 
# prints & # 39; a & # 39;

print ( max (l))

 
# prints & # 39; ab & # 39;

print ( min (l))

Here you notice that the output is in lexicographic order. This way we can find output according to line length or requirement by simply passing in the function 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 explaining min () and max ()

l = [ "ab" , "abc" , "bc" , "c " ]

  

print ( max (l, key = len ))

print ( min (l, key = len ) )

Exit:

 abc c 

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

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

Exit :

 abc abc 

Another example:

# Python code explaining min () and max ()

l = [{ `name` : ` ramu` , `score` : 90 , `age` : 24 },

{ `name` : `golu` , ` score` : 70 , `age` : 19 }]

 
# here the anonymous function takes an element as an argument.

print ( max (l, key = lambda item: item.get ( `age` )))

Exit :

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

Similarly, we can use the min () function instead of the max () function as required.

Get Solution for free from DataCamp guru