The max()
function returns the largest item in an iterable or the largest of two or more arguments. It has two forms.
- max() function with objects
- max() function with iterable
max() function with objects
Unlike the max() function of C/C++, the max() function in Python can take any type of object and returns the largest among them. In the case of strings, it returns the lexicographically largest value.
Syntax : max(arg1, arg2, *args[, key])
Parameters :
- arg1, arg2 : objects of the same datatype
- *args : multiple objects
- key : function where comparison of iterable is performed based on its return value
Returns : The maximum value
Example 1 : Finding the maximum of 3 integer variables.
var1 = 4 var2 = 8 var3 = 2 max_val = max (var1, var2, var3) print (max_val) |
Output :
8
Example 2 : Finding the maximum of 3 string variables. By default it will return the string with the maximum lexographic value.
var1 = "geeks" var2 = "for" var3 = "geek" max_val = max (var1, var2, var3) print (max_val) |
Output :
for
Example 3 : Finding the maximum of 3 string variables according to the length. We will be passing a key function in the max()
method.
var1 = "geeks" var2 = "for" var3 = "geek" max_val = max (var1, var2, var3, key = len ) print (max_val) |
Output :
geeks
Example 4 : If we pass parameters of different datatypes, then a exception will be raised.
integer = 5 string = "geek" max_val = max (integer, string) print (max_val) |
Output :
TypeError: '>' not supported between instances of 'str' and 'int'
max() function with iterable
When an iterable is passed to the max() function it returns the largest item of the iterable.
Syntax : max(iterable, *iterables[, key, default])
Parameters :
- iterable : iterable object like list or string.
- *iterables : multiple iterables
- key : function where comparison of iterable is performed based on its return value
- default : value if the iterable is empty
Returns : The maximum value.
Example 1 : Finding the lexographically maximum character in a string.
string = "GeeksforGeeks" max_val = max (string) print (max_val) |
Output :
s
Example 2 : Finding the lexographically maximum string in a string list.
string_list = [ "Geeks" , "for" , "Geeks" ] max_val = max (string_list) print (max_val) |
Output :
for
Example 3 : Finding the longest string in a string list.
string_list = [ "Geeks" , "for" , "Geek" ] max_val = max (string_list, key = len ) print (max_val) |
Output :
Geeks
Example 4 : If the iterable is empty, the default value will be displayed.
dictionary = {} max_val = max (dictionary, default = { 1 : "Geek" }) print (max_val) |
Output :
{1: 'Geek'}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.