-4

I have following list:

cnames = [" green ", " blue ", " yellow ", " gray ", " pink ", " orange ", "purple ", " red ", "brown "]

How do I get 6 random and unique indexes representing a number between 0 and len(cnames) from that list?

dasranke
  • 13
  • 1
  • can you use numpy or any other library? – Ivan Mar 12 '18 at 15:25
  • 4
    Possible duplicate of [Index of a random item from a list](https://stackoverflow.com/questions/49236418/index-of-a-random-item-from-a-list) – Rakesh Mar 12 '18 at 15:30
  • 1
    Not only is this an exact duplicate, it was asked by the same user 2 hours ago, and marked a duplicate then as well. @dasranke please refrain from asking the same duplicate questions multiple times. – user3483203 Mar 12 '18 at 15:31
  • 1
    Possible duplicate of [how to randomly select an item from a list](https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list); @Rakesh's link is already marked as a duplicate of this one. – Prune Mar 12 '18 at 15:32

2 Answers2

2

You can use python standard library random and its function sample:

import random

print(random.sample(range(len(cnames)), 6))
Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59
1

You can use random.shuffle(list) method, and pop() method on the list. Here is an example:

>>> cnames = ["red", "green", "blue", "grey", "orange"]
>>> import random
>>> random.shuffle(cnames)
>>> cnames.pop()
'green'
>>> cnames.pop()
'grey'
>>> cnames.pop()
'red'
>>> cnames
['blue', 'orange']
>>> 
Laszlowaty
  • 1,295
  • 2
  • 11
  • 19