.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