Get a random sample with replacement

I have this list:

colors = ["R", "G", "B", "Y"]

and I want to get 4 random letters from it, but including repetition.

Running this will only give me 4 unique letters, but never any repeating letters:

print(random.sample(colors,4))

How do I get a list of 4 colors, with repeating letters possible?


Solution 1:

In Python 3.6, the new random.choices() function will address the problem directly:

>>> from random import choices
>>> colors = ["R", "G", "B", "Y"]
>>> choices(colors, k=4)
['G', 'R', 'G', 'Y']

Solution 2:

With random.choice:

print([random.choice(colors) for _ in colors])

If the number of values you need does not correspond to the number of values in the list, then use range:

print([random.choice(colors) for _ in range(7)])

From Python 3.6 onwards you can also use random.choices (plural) and specify the number of values you need as the k argument.

Solution 3:

Try numpy.random.choice (documentation numpy-v1.13):

import numpy as np
n = 10 #size of the sample you want
print(np.random.choice(colors,n))