max() Function With iterable In Python
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 Lexicographically Maximum Character in a String
This code defines a string “w3wiki” and then uses the max()
function to find and print the character with the highest Unicode value within the string, which is ‘s’.
Python3
string = "w3wiki" max_val = max (string) print (max_val) |
s
Example 2: Finding the Lexicographically Maximum String in a String List
This code creates a list of strings, “string_list,” containing [“Geeks”, “for”, “Geeks”]. It then uses the max()
function to find and print the maximum string based on lexicographic order
Python3
string_list = [ "Geeks" , "for" , "Geeks" ] max_val = max (string_list) print (max_val) |
for
Example 3: Finding the Longest String in a String List
In this code, there is a list of strings, “string_list,” containing [“Geeks”, “for”, “Geek”]. It utilizes the max()
function with the key=len
argument, which compares the strings based on their lengths.
Python3
string_list = [ "Geeks" , "for" , "Geek" ] max_val = max (string_list, key = len ) print (max_val) |
Geeks
Example 4: If the Iterable is Empty, the Default Value will be Displayed
This code initializes an empty dictionary, “dictionary,” and then uses the max()
function with the default
argument set to a default value, which is the dictionary {1: "Geek"}
.
Python3
dictionary = {} max_val = max (dictionary, default = { 1 : "Geek" }) print (max_val) |
{1: 'Geek'}
Python – max() function
Python 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