Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 915
Spark_101 Avatar asked Jan 01 '26 01:01

Spark_101


2 Answers

It is easiest to just apply logic to the entire list. You can get the max value of a list using max(list), and you can use the same index function you use above to get the index of this number in the list.

max_val = max(list_c)
idx_max = list_c.index(max_val)

If you want to loop over the values to find the max, then take note of the following:

  1. list.index(value) will find the index of that value in the list. In your case you are writing list.index(index_number) which doesnt make sense. 'i' already represents the list index, so just set idx_max = 'i'.

  2. Further, you should note that if you set max_val to zero, if all the list items are less than zero, it will stay at zero during the loop and never find the max value. It is better to start by setting max_val to the first item of the list ie list_c[0].

     list_c = [-14, 7, -9, 2]
    
     max_val = list_c[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
    

NB 'return' is used to return values from a function. If you want to print the values, use print(list_c, max_val, idx_max).

like image 100
Daniel Redgate Avatar answered Jan 03 '26 15:01

Daniel Redgate


Looping twice through an array is inefficient. Use built-in enumerate() and max() with the comparison lambda expression returning the second element of the enumeration:

>>> list_c = [-14, 7, -9, 2]
>>> print(max(enumerate(list_c), key=lambda x: x[1]))
(1, 7)
like image 40
user1602 Avatar answered Jan 03 '26 14:01

user1602



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!