You can use a list-comprehension
with enumerate()
. With thanks to @MikeScotty
, a performance improvement would be to calculate the smallest value first.
Here's the code:
mn = min(A)
[i for i,e in enumerate(A) if e == mn]
which gives:
[2, 5]
which are the indexes of the 1s
in A
- not [2, 8]
To prove this is faster, here's the minx
wrapper
:
>>> def minx(l):
... print("called")
... return min(l)
...
>>> [i for i,e in enumerate(A) if e == minx(A)]
called
called
called
called
called
called
called
called
called
[2, 5]
And some timings using timeit
:
>>> timeit.timeit("[i for i,e in enumerate(A) if e == min(A)]", globals=locals())
5.9568054789997404
>>> timeit.timeit("[i for i,e in enumerate(A) if e == 1]", globals=locals())
1.397674421001284