Find Maximum Value in a List in Python

In this tutorial, we will learn how to find the maximum value in a Python list. It will cover a variety of different methods for achieving this as well as getting the max value in nested lists.


The max() Function

The build-in Python max() function is the simplest way for getting the highest value from a list. Below is an example of getting the largest number in a list:


numbers = [1, 6, 12, 9, 7]

result = max(numbers)



Get Index of the Maximum Value in a List

To get the index of the maximum value in a list, use the Python arr.index() function in conjunction with the max() function like this:


numbers = [1, 6, 12, 9, 7]

result = numbers.index(max(numbers))



As you are probably aware list indexes start at 0 which is why 2 is the result in the above example.


Find Max Value in a Nested List in Python

Let's say we have a list of nested lists and would like to evaluate what is the maximum value in the second nested list. In that scenario, we could use the key argument in max() and use a lambda function to specify which index.


numbers = [ [1, 12], [3, 6], [1, 2] ]

idx, max_val = max(numbers, key=lambda x: x[1])

print(f'{max_val} at index {idx}')
12 at index 1


Get Max List Value with for Loop

With a for loop, we can iterate over a list and set the value of a variable to the current iteration value if it is great than the current variable value.


numbers = [1, 6, 12, 9, 7]

max_val = None
for v in numbers:
   if (max_val is None or v > max_val):
       max_val = v