Search code examples
pythonfor-loopindexingelement

How to find the index of the max value in a list for Python?


I have a list, and I need to find the maximum element in the list and also record the index at which that max element is at.

This is my code.

list_c = [-14, 7, -9, 2]

max_val = 0
idx_max = 0

for i in range(len(list_c)):
    if list_c[i] > max_val:
        max_val = list_c[i]
        idx_max = list_c.index(i)

return list_c, max_val, idx_max

Please help. I am just beginning to code and got stuck here.


Solution

    • You are trying to find the index of i. It should be list_c[i].

    Easy way/Better way is: idx_max = i. (Based on @Matthias comment above.)

    • Use print to print the results and not return. You use return inside functions.
    • Also your code doesn't work if list_c has all negative values because you are setting max_val to 0. You get a 0 always.
    list_c = [-14, 7, -9, 2]
    
    max_val = 0
    idx_max = 0
    
    for i in range(len(list_c)):
        if list_c[i] > max_val:
            max_val = list_c[i]
            idx_max = i
    
    print(list_c, max_val, idx_max)
    
    
    [-14, 7, -9, 2] 7 1