max(arg1,arg2, key=my_fun )
arg1, arg2 :numbers , iterable inputs or more than one inputs
key=my_fun : built-in functions or user defined functions based on which the maximum value can be returned.
Return value is the highest value or list with highest positional element (or highest based on the input function).
Using numbers
x=4
y=7
print(max(x,y)) # 7
Using list
my_list=[1,2,3,4,5]
print(max(my_list)) # 5
Using string
max() returns based on alphabetical order.
my_list=['Hello','Welcome','To','Plus2net']
print(max(my_list)) # Welcome
my_list=['Hello','Welcome','to','plus2net']
print(max(my_list)) # to
Using Dictionary
Output depends on Keys of the Dictionary ( Not Values ).
my_dict={1:'A',2:'B',3:'C'}
print(max(my_dict)) # 3
Getting highest key value pair based on value of the dictionary
Student Name and mark is stored in a dictionary, collect the student who got the highest mark.
my_dict={'Raju':45,'Ronn':56,'Tom':50}
key_of_max_value = max(my_dict, key=my_dict.get)
print(key_of_max_value,my_dict[key_of_max_value])
Output is here
Ronn 56
We will use tuple
my_tuple=(6,1,12,7)
print(max(my_tuple)) #12
Using more than one list
my_list1=[4,7,8,9]
my_list2=[5,1,1]
print(max(my_list2,my_list1)) # [5, 1, 1]
More than two lists
my_list1=[4,7,8,9]
my_list2=[5,1,1]
my_list3=[6,1,-3]
print(max(my_list2,my_list1,my_list3)) # [6, 1, -3]
Here comparison is done from left to right and based on the position of the first highest element the list is returned as maximum.
Check the below code, since first element is equal in all three lists , the comparison is done based on the 2nd element and the list with highest value at 2nd position is returned by max() function.
my_list1=[4,7,8,9]
my_list2=[4,1,1]
my_list3=[4,1,-3]
print(max(my_list2,my_list1,my_list3)) # [4, 7, 8, 9]
Using the key
We can use any built-in function like sum or len to get the list with maximum value.
my_list1=[4,2,3,7,8,9]
my_list2=[5,1,100]
print(max(my_list2,my_list1,key=sum)) # [5, 1, 100]
Using Len
my_list1=[4,2,3,7,8,9]
my_list2=[5,1,100]
print(max(my_list2,my_list1,key=len)) # [4, 2, 3, 7, 8, 9]
Based on UDF
We will use one user defined function to find out the last number of the input list and based on this last number we can get the list with highest number.
def last_digit(my_list):
return my_list[-1] # last digit
my_list1=[4,2,3,7,8,9]
my_list2=[25,41,1]
print(max(my_list2,my_list1,key=last_digit)) #[4, 2, 3, 7, 8, 9]
« min()
Iterator »
any() »
← Subscribe to our YouTube Channel here