1

I have to get the smallest value from a list of monthly precipitation stats, then find the index of that element, then get the element with the same index value from a dictionary. This is the part of the code that is supposed to do this:

# finds the minimum precipitation from user's inputs and finds the corresponding month
min_precipitation = min(precipitation_by_month)
lowest_precipitation = precipitation_by_month.index(min_precipitation)
lowest_precipitation_month = months.pop(lowest_precipitation)
print (lowest_precipitation_month, 'has the lowest precipitation:', "{:.2f}".format(min_precipitation), 'inches.')

The problem is that in one of the inputs for this HW there are two 0.00 values in the list, but the program gets the second 0.00 value instead of the first (which is required) and therefore the wrong index number too.

Am I doing something wrong? How can I fix this?

pythonoob
  • 13
  • 4
  • 1
    This is not reproducible, the program *never* gets the second value. `min` is stable (like Python sorting in general), and always returns the first copy of equal values. Even if it didn't, the `.index` call works from left to right and stops when it gets a hit, so you'd always pop out the first of the two values. So either this isn't your real code ([MCVE] that aren't actually reproducing the problem are useless), or your inputs aren't what you claim they are (are they actually two numbers that aren't *quite* zero, and the second is legit smaller?). – ShadowRanger Feb 04 '21 at 22:42
  • 1
    You can verify stability pretty easily thanks to the existence of `-0.0`; `-0.0 == 0.0` is true, and `min([-0.0, 0.0])` always produces `-0.0` (because it appears first), while `min([0.0, -0.0])` always gets `0.0` (again, it appears first). – ShadowRanger Feb 04 '21 at 22:46
  • @pythonoob What makes you say "the program gets the second 0.00 value instead of the first"? Can you provide example inputs and outputs? – Paul M. Feb 04 '21 at 22:47
  • 1
    If you're using floats, have you checked for floating-point errors? Your output formatting will hide small differences. – ekhumoro Feb 04 '21 at 23:07

2 Answers2

0

Just use the list.index method with the min(list) method and you will get index of the first smallest number in the list:

n = [0,1,2,3,0]

print(n.index(min(n)))

Output:

Index is: 0
Jakub Szlaur
  • 1,344
  • 7
  • 23
-1

This question has already been answered: Index of multiple minimum elements in a list

Find the minimum value, and then iterate through the list matching with the minimum value to access each one.

  • 1
    If you believe it's a duplicate, flag it as such, don't post an answer duplicating the answers to the duplicate. That said, it's not a duplicate; they want the first minimum, not the rest, so they don't need anything complicated. The question is wrong (it thinks something is happening that definitely isn't), but it's not a duplicate of the one you link. – ShadowRanger Feb 04 '21 at 22:49