You've tagged this as numpy
, and describe a shape
(not len
). Which leads me to think you have a numpy array.
In [665]: x=np.random.rand(10)
In [666]: x
Out[666]:
array([ 0.6708692 , 0.2856505 , 0.19186508, 0.59411697, 0.1188686 ,
0.54921919, 0.77402055, 0.12569494, 0.08807101, 0.11623299])
In [667]: x>.5
Out[667]: array([ True, False, False, True, False, True, True, False, False, False], dtype=bool)
In [668]: list(x).index(.6708692)
ValueError: 0.6708692 is not in list
The reason for the ValueError
is that you are looking for a float, and those often don't exactly match. If the array was of ints, then such an index would work.
In [669]: list(np.arange(10)).index(5)
Out[669]: 5
This reasoning applies whether x
was an array or a list.
numpy
has a where
that returns the index of boolean true values in an array
In [670]: np.where(x>.5)
Out[670]: (array([0, 3, 5, 6], dtype=int32),)
x>.5
is the boolean array as shown above, and [0,3,5,6]
the index values where this is true.
In [671]: x[np.where(x>.5)]
Out[671]: array([ 0.6708692 , 0.59411697, 0.54921919, 0.77402055])
The equality test doesn't work any better
In [672]: x[np.where(x==0.6708692)]
Out[672]: array([], dtype=float64)
For floats there is the concept of close
- the difference is within some tolerance (np.allclose
is particularly useful):
In [679]: np.where(np.isclose(x,0.59411697))
Out[679]: (array([3], dtype=int32),)
For lists, one of the enumerate solutions is great, and also works with 1d arrays. But it is already an array, use the where
.