Python max function

In this post, we will see about python max function.
Python max() function returns max value in iteable or passed arguments.


Let’s understand both with the help of examples.


It returns max value from iterable or passed arguments
Let’s see a very simple example:

#Max in the list l=[9,5,14,2,3] print("Max in list:",max(l)) #Max in list of String lStr=['John','Martin','Sam','Mary'] print("Max in list of String:",max(lStr)) #Max in tuple t=(1,3,23,21,7) print("Max in tuple:",max(t)) #Max in arguments print("Max among 21,25:",max(21,25)) print("Max among 31,39,37:",max(31,39,37)) #If different type of argument in the list l=[3,6,4,'Apple','Orange'] #If different type of argument in the list print(max(l))


Max in list: 14
Max in list of String: Sam
Max in tuple: 23
Max among 21,25: 25
Max among 31,39,37: 39
TypeError Traceback (most recent call last)
in ()
18 l=[3,6,4,’Apple’,’Orange’]
19 #If different type of argument in the list
—> 20 print(max(l))

TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

As you can see if we have different data type in the list, it raise TypeError.
Let’s see how can we use key attribute in max function.

def checkLen(num): return len(str(num)) # It will return max number of digits print(max(134,2,12321,43,1110,key=checkLen)) # It will return list with max length l1=[1,2,3] l2=[4,5] print(max(l1,l2,key=len))


[1, 2, 3]

That’s all about python max function.

Leave a Reply

Your email address will not be published. Required fields are marked *