Python List max() Method
The Python List max() method compares the elements of the list and returns the maximum valued element.
If the elements in the list are numbers, the comparison is done numerically; but if the list contains strings, the comparison is done alphabetically.
Note: The comparison in this method is only performed among same data types. If the list contains elements of multiple types, a TypeError is raised.
Syntax
Following is the syntax for the Python List max() method −
max(list)
Parameters
list − A list from which the max valued element is to be returned.
Return Value
This method returns the maximum value from a list.
Example
The following example shows the usage of the Python List max() method. The method performs alphabetical comparison on the string elements of the list created.
list1 = ['123', 'xyz', 'zara', 'abc']
print("Max value element : ", str(max(list1)))
When we run above program, it produces following result −
Max value element : zara
Example
Now let us find the maximum number in a list containing only numbers in the example below.
list2 = [456, 700, 200]
print("Max value element : ", str(max(list2)))
If we compile and run the given program, the output is displayed as follows −
Max value element : 700
Example
If the list contains multiple data type elements, the method fails to retrieve a maximum valued element as the comparison is not possible between two different data types.
list1 = [123, 'xyz', 'abc', 456]
print("Max value element : ", str(max(list1)))
Once we compile and run the program above, the TypeError is raised.
Traceback (most recent call last): File "main.py", line 2, inprint("Max value element : ", str(max(list1))) TypeError: '>' not supported between instances of 'str' and 'int'
Example
In this example, let us consider a real-time scenario where this method might come in handy. We are creating two lists: one containing student names and the other containing their marks in the corresponding index. The highest marks are found using the max() method and the corresponding index of the student with the highest marks is retrieved using the index() method. The student bearing the highest marks has to be announced as the topper.
marks = [880, 946, 934, 989, 781] student = ['Jason', 'John', 'Alex', 'Chris', 'Alice'] rank_1 = max(marks) name_id = marks.index(max(marks)) print(str(student[name_id]), "ranked first with", str(rank_1), "marks")
If we execute the program above, the output is achieved as follows −
Chris ranked first with 989 marks