Python 3 – List max() Method
In Python, the max() method is used to find the maximum element in a list. It returns the largest element in a list.
Syntax
The syntax of the max() method is:
max(iterable, *iterables, key, default)
Here,
iterable
– Required. An iterable sequence like list, tuple or string etc.*iterables
(Optional) – Any number of iterable sequences like list, tuple, string etc.key
(Optional) – In case if a collection contains nested lists or tuples,key
is used to specify a function of one argument to extract a comparison key from each element in the given iterable.default
(Optional) – The value to be returned in case the iterable is empty.
Example 1:
Here is an example demonstrating the use of the max() method.
Code:
numbers = [1, 4, 2, 8, 9, 10]
print("Maximum of numbers:", max(numbers))
Output:
Maximum of numbers: 10
In the above example, we have a list of integers named numbers
. We are using the max() method to find the maximum element in the list, and then we are printing the maximum value.
Example 2:
Here is one more example demonstrating the use of the max() method with a key.
Code:
names = ["apple", "ball", "cat", "dog", "elephant", "fish", "gun"]
print("Longest name is:", max(names, key=len))
Output:
Longest name is: elephant
In the above example, we have a list of strings named names
. We also passed the key=len
argument to the max() method. This means it will consider the length of each element in the list to find the maximum value. In this case, “elephant” is the longest name in the list and it’s length is 8.
Example 3:
Here is an example demonstrating the use of the max() method with multiple iterables and default value.
Code:
list1 = [5, 3, 6, 9, 7]
list2 = [2, 4, 1, 8, 10]
# Using the max() method with multiple iterables
maximum = max(list1, list2)
print("Largest value:", maximum)
# Using the max() method with an empty iterable and default value
empty_list = []
# Here, the max() method will return the default value as there are no elements in the empty_list.
print("Max value in empty list:", max(empty_list, default=0))
Output:
Largest value: [5, 3, 6, 9, 7]
Max value in empty list: 0
In the above example, we have two lists named list1
and list2
. We passed both the lists to the max() method as arguments. The max() method is clever enough to the compare the maximum elements across both the lists and return the maximum value. Here, it returned the entire list1
as it has the largest element.
We then create an empty list named empty_list
and passed it to the max() method by specifying a default value of 0. Since the list is empty, the method returns the default value we specified.
Conclusion
Hence, we have learned how to use the Python’s max() method to find the maximum element in a list. The max() method is powerful enough to handle scenarios like multiple iterables and nested lists as well.