Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Find index of minimum item in list of floats [duplicate]

How can I find the index of the minimum item in a Python list of floats? If they were integers, I would simply do:

minIndex = myList.index(min(myList)) 

However, with a list of floats I get the following error, I assume because float equality comparison is rather iffy.

ValueError: 0.13417985135 is not in list 

Now, I know that I could simply scroll through the list and compare each item to see whether it is < (min + 0.0000000000001) and > (min - 0.0000000000001), but that is kinda messy. Is there a more elegant (preferably built-in) way to find the index of the smallest item in a list of floats?

like image 339
thornate Avatar asked Nov 09 '12 01:11

thornate


People also ask

How do you find the index of the minimum value of a list in 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 you find the index of minimum value in a list?

Python's inbuilt function allows us to find it in one line, we can find the minimum in the list using the min() function and then use the index() function to find out the index of that minimum element.


2 Answers

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list)) 

Then val will be the minimum value and idx will be its index.

like image 104
David Wolever Avatar answered Sep 17 '22 12:09

David Wolever


You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter min(enumerate(a), key=itemgetter(1))[0]  
like image 31
Jon Clements Avatar answered Sep 17 '22 12:09

Jon Clements