0

If I have a list such as:

a = [1, 2, 3, 3, 4, 5]

And I want to choose a random element from this list using np.random.choice, and let's say that results in me getting the value 3, how am I supposed to get the correct index of the element 3 and not just automatically the first 3 that appears?

I know for list of unique values, I can use .index to get it, but not sure how to go about for non-unique values.

Thanks!

glS
  • 1,209
  • 6
  • 18
  • 45
jyc
  • 1
  • 1
  • Possible duplicate of [How to find all occurrences of an element in a list?](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Łukasz Rogalski Dec 02 '16 at 12:09
  • So, are you trying to get the index of a `3` picked at random? – Divakar Dec 02 '16 at 12:09
  • 2
    Then you choose the index randomly and get the item from the index. – Klaus D. Dec 02 '16 at 12:10
  • 1
    Possible duplicate of [how to get the index of numpy.random.choice? - python](http://stackoverflow.com/questions/18794390/how-to-get-the-index-of-numpy-random-choice-python) – Julien Marrec Dec 02 '16 at 12:13
  • Hi Julien and Lukasz, so np.random.choice and then getting the index would work if the value that was outputted is non-unique. Then I would get the correct index. – jyc Dec 02 '16 at 20:29
  • To @Divakar, yes if that 3 was picked at random, how would I know whether it was the 3 from index 2 or index 3? – jyc Dec 02 '16 at 20:30

1 Answers1

6

You can't, of course. If you need the index for a picked value, you'd rather choose a random index first and then retrieve the desired list element:

index = random.randrange(0, len(a))
value = a[index]

Note that using the .index approach is not that good even if the element is unique, since that method has to perform a linear search on the list (i.e. comparing each element with your value until it is found out)

jsbueno
  • 99,910
  • 10
  • 151
  • 209