-5

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
  • 1
  • 2
  • Just for clarity, what do you mean by 6 random and unique indexes? Do you mean 6 unique integers representing a number between `0` and `len(cnames)` or 6 unique strings matching strings in the list? – Garrett Gutierrez Mar 12 '18 at 13:33
  • @GarretGutierrez I mean 6 unique integers representing a number between 0 and len(cnames) – dasranke Mar 12 '18 at 13:40
  • `random.sample(range(len(cnames),k=6)` will sample without replacement 6 numbers between 0 and len(cnames). U can use `choices(...)` if you want them with replacement. – Patrick Artner Mar 12 '18 at 14:58

1 Answers1

2

The random module should help.

import random
random.sample(cnames, 6)   #random.sample returns unique list of random choice. 

random.sample(range(len(cnames)), 6)#to get random int representing a number between 0 and len(cnames)

Output:

[' gray ', ' pink ', 'purple ', ' blue ', ' orange ', ' green ']
Rakesh
  • 81,458
  • 17
  • 76
  • 113