The max() function in Python is a built-in function that returns the maximum value from a sequence of values or an iterable object such as a list, tuple, or set. This function can also accept one or more arguments and return the largest of those values.
In this article, I will explain the Python max() function and using its syntax, parameters, and usage how you can find the maximum element from a given list, tuples, sets, and dictionaries with examples.
1. Quick Examples of max() Method
If you are in a hurry, below are some quick examples of the Python max() function.
# Quick examples of max() method
# Example 1: Find the maximum element in a string
# Using the max() function
mystring =[‘Python’,’Spark’,’Java’,’Hadoop’]
max_value = max(mystring)
# Example 2: Find the maximum element in a list
# Using the max() function
mylist =[20, 10, 30, 5]
max_value = max(mylist)
# Example 3: Find the maximum element in a tuple
# Using the max() function
mytuple = (20, 10, 30, 5)
max_value = max(mytuple)
# Example 4: Find the maximum element in a set
# Using max() function
myset = {20, 10, 30, 5}
max_value = max(myset)
# Example 5: Using the max() function over the dictionaries
# get maximum key:value pair
mydict = {‘Python’: 2000, ‘Spark’: 1000, ‘Hadoop’: 2500}
max_key1 = max(mydict)
print(“The maximum key of the dictionary: “, max_key1)
# Get the key whose value is maximum
max_key2 = max(mydict, key = lambda x: mydict[x])
# Example 6: Find the string with maximum length
mylist =[‘Python’,’Spark’,’Java’,’Hadoop’]
max_string = max(mylist, key=len)
# Example 7: Use maximum empty list
mylist =[]
max_value = max(mylist)
# Example 8: Use max() function
# Default value 0
mylist =[]
max_value = max(mylist, default=0)
# Example 9: Find the maximum element from both lists
# Using the max() function
mylist1 = [5, 10, 20, 30]
mylist2 = [10, 15, 25, 35]
max_value = max(mylist1, mylist2)
# Example 10: Use min() function
# With multiple arguments
a = 5
b = 3
c = 8
max_val = max(a, b, c)
# Example 11: Find the maximum float value
# Using the max() function
float_list = [3.14, 2.71, 5.618, 4.71828]
max_float = max(float_list)
# Example 12: Using max() exception
integer = 20
string = “SarkbyExamples”
max_val = max(integer, string)
2. Python max() Function
In Python, the max() function allows one or more iterable objects and returns the largest item. If the iterable object is the values of a string, comparison can be done alphabetically. Moreover, it allows two or more parameters and finds the largest item among them.
2.1 Syntax of max() Method with Iterable
Following is the syntax of the max() method.
# Syntax of max() function
max(iterable, *iterables[, key, default])
2.2 Parameter of max() method
iterable – (Required) This is the iterable object(e.g. list, tuple, set, etc.) from which you want to find the maximum value.
*iterables – Any number of iterables can be passed into this function.
key – key function where the iterables are passed and comparison is done based on its return value
default – default is the value to return if the iterable is empty. The default value is None.
2.3 Return Value
It returns the maximum element from an iterable, such as a list, tuple, or set.
3. Using max() Function On List & Get Max Value
You can find the maximum element in a list of strings using the max() function. It will return the string with the highest lexicographical value. For Example, this function returns Spark as the maximum element because it has the highest lexicographical value among the strings in the list.
# Initialize the list
mystring =[‘Python’,’Spark’,’Java’,’Hadoop’]
print(“Original list: “, mystring)
# Find the maximum element in list of string
# Using the max() function
max_value = max(mystring)
print(“The maximum element of string is: “, max_value)
Yields below output.
3.1 Find the Max Element in the List of Numbers
Apply the max() function over the list of numbers to find the maximum element in a list. For example, first, initialize a list mylist with four elements, [20, 10, 30, 5]. After that, you can use this function to find the maximum element of the given list and assign it to the variable max_value.
# Initialize the list
mylist =[20, 10, 30, 5]
print(“Original list: “, mylist)
# Find the maximum element in a list
# Using the max() function
max_value = max(mylist)
print(“The maximum element of the list is:”, max_value)
Yields below output.
3.2 Find the Maximum Element in a Tuple Using max()
You can also find out the maximum element in a tuple using the max() function. Let’s pass the tuple as an argument to this function to get the maximum element from the tuple.
# Initialize the tuple
mytuple = (20, 10, 30, 5)
print(“Original tuple:”, mytuple)
# Find the maximum element in a tuple
# Using the max() function
max_value = max(mytuple)
print(“The maximum element of the tuple is:”, max_value)
# Output:
# Original tuple: (20, 10, 30, 5)
# The maximum element of the tuple is: 30
As you can see, from the above 30 has been returned as the maximum value of given tuple.
3.3 Get the Maximum Element in Set Using max()
Similarly, you can get the maximum element in a set using the max() function, you can pass the set as an argument to this function, which will return the largest element from a given set. For example, the original set {20, 10, 30, 5}. The max() function is then used to find the maximum value in the set, which is 30.
# Initialize the set
myset = {20, 10, 30, 5}
print(“Original set:”, myset)
# Find the maximum element in a set
# Using max() function
max_value = max(myset)
print(“The maximum element of the set is:”, max_value)
# Output:
# Original set: {10, 20, 5, 30}
# The maximum element of the set is: 30
3.4 Using the max() Function over the Dictionaries
You can also find the largest element in dictionaries using the max() function. In dictionaries, you can find out the maximum value through the keys. If you want to find the key whose value is maximum, you can customize the key function of the max() function.
For example, first, initialize a dictionary named mydict with three key-value pairs. The keys are strings (‘Python’, ‘Spark’, and ‘Hadoop’) and the values are integers (2000, 1000, and 2500). Then, apply the max() function over the dictionary named mydict to find the largest element in the dictionary where the largest element is considered as the largest key of the dictionary.
# Initialize the dictionary
mydict = {‘Python’: 2000, ‘Spark’: 1000, ‘Hadoop’: 2500}
print(“Original dictionary: “, mydict)
# Get maximum key in dict
# Using the max() function
max_key1 = max(mydict)
print(“The maximum key of the dictionary: “, max_key1)
# Get the key whose value is maximum
max_key2 = max(mydict, key = lambda x: mydict[x])
print(“Get key whose value is maximum:”, max_key2)
print(“Maximum value of dictionary:”, mydict[max_key2])
Yields below output.
# Output:
Original dictionary: {‘Python’: 2000, ‘Spark’: 1000, ‘Hadoop’: 2500}
The maximum key of the dictionary: Spark
Get key whose value is maximum: Hadoop
Maximum value of dictionary: 2500
4. Find the String with Maximum Length
You can also find the string with the maximum length in a list of strings, you can use the max() function with a custom key function that returns the length of each string. In the below example, first, initialize a list mylist with four elements. This function is used to find the string with the maximum length by specifying key=len. The key argument tells the function to consider the length of each string when determining the maximum value.
# Initialize the list
mylist =[‘Python’,’Spark’,’Java’,’Hadoop’]
print(“Original list: “, mylist)
# Find the string with maximum length
max_string = max(mylist, key=len)
print(“The string with the maximum length is:”, max_string)
# Output:
# Original list: [‘Python’, ‘Spark’, ‘Java’, ‘Hadoop’]
# The string with the maximum length is: Python
5. Get ValueError Exception
If you find the maximum value of an empty list using the max() function, it will return a ValueError with the message “max() arg is an empty sequence“. This is because there is no maximum value to find in an empty list.
# Initialize list
mylist =[]
# Use maximum empty list
max_value = max(mylist)
print(max_value)
# Output:
# Traceback (most recent call last):
# File “./prog.py”, line 5, in <module>
# ValueError: max() arg is an empty sequence
6. Use max() Function with Default Value
If you want to avoid ValueError when using max() over the empty list, you can provide a default value with the specified value. For example, you use the max() function with the default parameter set to 0. This means that if mylist is empty, the max() function will return 0 instead of raising a ValueError.
# Initialize the list
mylist =[]
# Use max() function
# Default value 0
max_value = max(mylist, default=0)
print(“Largest number in the list is”, max_value)
# Output:
# Largest number in the list is 0
7. Use the max() Function with Multiple Iterables
The max() function can also be used with multiple iterables by passing them as separate arguments. It will compare corresponding elements from each iterable and return the maximum element based on their natural order.
In the below example, you have two lists, mylist1 and mylist2. Bypassing both lists as arguments to the max() function, it compares corresponding elements from both lists and returns the maximum element based on their natural order.
# Define two lists
mylist1 = [5, 10, 20, 30]
mylist2 = [10, 15, 25, 35]
# Find the maximum element from both lists
# Using the max() function
max_value = max(mylist1, mylist2)
print(“The maximum element from both lists: “, max_value)
# Output:
# The maximum element from both lists: [10, 15, 25, 35]
You can also use the max() function with multiple arguments to find the largest element among them. For example, you have three variables a, b, and c, which have the values 5, 3, and 8, respectively. You can use the max() function with these variables as arguments to find the largest value among them, which is 8.
# Use min() function
# With multiple arguments
a = 5
b = 3
c = 8
max_val = max(a, b, c)
print(“The largest element is: “,max_val)
# Output:
# The largest element is: 8
8. Find the Maximum Element in a Float Using max()
You can also find the maximum element in a float using the max() function, you need to pass an iterable containing the float values as an argument. For example, you have a list float_list containing float values. By passing float_list as an argument to the max() function, it compares all the float values and returns the maximum element. In this case, the maximum float value is 5.618.
# Define a list of float values
float_list = [3.14, 2.71, 5.618, 4.71828]
# Find the maximum float value
# Using the max() function
max_float = max(float_list)
print(“The maximum float value: “, max_float)
# Output:
# The maximum float value: 5.618
9. Using max() exception
You can pass different types of data types into the max() function, it will raise the TypeError. Because this function can only compare elements of the same type. In this case, the max() function cannot compare an integer with a string.
integer = 20
string = “SarkbyExamples”
# Using max() exception
max_val = max(integer, string)
print(max_val)
# Output:
# Traceback (most recent call last):
# File “./prog.py”, line 4, in <module>
# TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
10. Conclusion
In this article, I have explained the Python max() function and using its syntax, parameters, and usage how to find the maximum element from iterable objects(such as a list, set, tuple, string, or dictionary. Also explained how it can return the max value when we pass the multiple iterables as its arguments with examples.
Happy Learning !!
The max() function in Python is a built-in function that returns the maximum value from a sequence of values or an iterable object such as a list, tuple, or set. This function can also accept one or more arguments and return the largest of those values. In this article, I will explain the Python max() Read More Python, Python Tutorial, Pending review by admin, Python Basics