How to Find the Index of the Max Value in a List in Python

by | Programming, Python, Tips

The maximum value in a list is the element with the highest value. You can find the maximum value index in a list by passing the list to the built-in max() function and then using list.index(element) where the element is the max value. The list.index() method will return the index of the first occurrence of the maximum value.


Example: List of Numbers

Let’s look at an example of finding the index of the max value in a list of numbers.

# Define list

my_list = [2, 5, 10, 99, 4]

# Get max value of the list

max_val = max(my_list)

# Get index of max value

max_idx = my_list.index(max_val)

# Print result

print(f'Max value in {my_list} is {max_val}, with the index {max_idx}')

Let’s run the code to get the result:

Max value in [2, 5, 10, 99, 4] is 99, with the index 3

Note that the index of a list starts from 0.

Example: List of Characters

We can also use the max value for characters, for example,

# Define string

my_str = 'fortyfive'

# Convert string to list of characters

my_list = list(my_str)

# Get maximum ASCII value

max_val = max(my_list)

# Get the index for the maximum value

max_idx = my_list.index(max_val)

# Print the result

print(f'Max value in {my_list} is {max_val}, with the index {max_idx}')

In the case of characters, the max() function will find the character with the maximum ASCII value. Let’s run the code to get the result:

Max value in ['f', 'o', 'r', 't', 'y', 'f', 'i', 'v', 'e'] is y, with the index 4

Summary

Congratulations on reading to the end of this tutorial!

For further reading on getting the index of a value from a list, go to the article:

How to Find the Index of the Min Value in a List in Python

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee