Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Finding Index of Maximum in List

def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    print max

if __name__ == '__main__':
    main()

I am able to get the maximum value in the array (without using max() of course...). How can I get the index (position) of that value? Please try to keep it simple without using new Python key words or built-in functions. Thanks!

like image 452
Shankar Kumar Avatar asked Jul 17 '12 21:07

Shankar Kumar


People also ask

How do you get the index of the max in a list Python?

Use the enumerate() function to find out the index of the maximum value in a list. Use the numpy. argmax() function of the NumPy library to find out the index of the maximum value in a list.

How do you find the index of the minimum value in a list Python?

The python has a built-in function of min() which returns the minimum value in the list and index() which returns the index of the element. These two functions can be used to find the index of a minimum element in a single line code.

How do I get Arg Max in Python?

Use np. arange() function to create an array and then use np argmax() function. Let's use the numpy arange() function to create a two-dimensional array and find the index of the maximum value of the array.


2 Answers

In my code I would use this:

>>> max(enumerate(a),key=lambda x: x[1])[0]
3
like image 50
ovgolovin Avatar answered Oct 18 '22 07:10

ovgolovin


A simple one liner of:

max( (v, i) for i, v in enumerate(a) )[1]

This avoids having to .index() the list after.

like image 22
Jon Clements Avatar answered Oct 18 '22 08:10

Jon Clements