2

I have a list of numbers and I want to print all indices at which the minimum value can be found.

My Attempt:

myList = [3, 2, 5, 7, 2, 4, 3, 2]

minValue = min(my_list)

my_list.count(minValue)

if mylist.count(minValue) > 1:
    for num in mylist:
        if num == minValue :
            print(my_list.index(minValue))

Actual Result:

1
1
1

Expected Result:

1
4
7

What am I doing wrong?

Brian Minton
  • 3,377
  • 3
  • 35
  • 41
Masoud_msd
  • 141
  • 1
  • 6

3 Answers3

3

Careful that your list has the same name everywhere, I fixed this for you in my example. Your problem can be solved by using enumerate() in your for loop.

my_list = [3, 2, 5, 7, 2, 4, 3, 2]

minValue = min(my_list)

my_list.count(minValue)

if my_list.count(minValue) > 1:
    for i, num in enumerate(my_list):
        if num == minValue :
            print(i)

Your problem was printing my_list.index(minValue), which always returns the first instance of the minValue, so the solution is to print the current index that the for loop is at for every item matching minValue.

schwartz721
  • 767
  • 7
  • 19
2

.index() returns index of the first occurrence of the element passed to it. You can use enumerate.

>>> my_list = [3, 2, 5, 7, 2, 4, 3, 2]
>>> min_val=min(my_list)
>>> for idx,val in enumerate(my_list):
        if val==min_val:
            print(idx)

Using range.

>>> my_list=[3, 2, 5, 7, 2, 4, 3, 2]
>>> min_val=min(my_list)
>>> for i in range(len(my_list)):
    if my_list[i]==min_val:
        print(i)        
1
4
7

As suggest in comments by Corentin Limier. You should use enumerate over range. Reference link.

The above can be written as list comprehension if you want to store the indices of the min value.

min_val=min(my_list)
min_indices=[idx for idx,val in enumerate(my_list) if val==min_val]
print(*min_indices,sep='\n')

output

1
4
7

Here's a numpy approach.

import numpy as np

my_list=np.array([3, 2, 5, 7, 2, 4, 3, 2])
x=np.where(my_list==my_list.min())
print(x)
print(*x[0],sep='\n')

output

(array([1, 4, 7], dtype=int64),)
1
4
7
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
1

What about using numpy?

np.argwhere(np.array(my_list)==min_value)
theletz
  • 1,713
  • 2
  • 16
  • 22