Get the index of the max value in a Python list

Here is an example of finding the index of the max value in a Python list.

s = [5, 6, 7, 4, 3]
t = [3, 4, 4, 1]

i = s.index(max(s))
j = t.index(max(t))

print(i)  # 2
print(j)  # 1

That is so simple but we can find only the first index of the maximum value. The following code shows how to get all the indices as a list.

s = [3, 4, 4, 1]

m = max(s)
a = []

for i, x in enumerate(s):
    if x == m:
        a.append(i)

print(a)  # [1, 2]

You can iterate the index and value of a Python list using enumerate() in the for statement. Or you can code using list comprehension.

s = [3, 4, 4, 1]

m = max(s)

a = [i for i, x in enumerate(s) if x == m]

print(a)  # [1, 2]

Python List

Python Tutorial