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?
With
random.choice
:If the number of values you need does not correspond to the number of values in the list, then use
range
:From Python 3.6 onwards you can also use
random.choices
(plural) and specify the number of values you need as the k argument.This code will produce the results you require. I have added comments to each line to help you and other users follow the process. Please feel free to ask any questions.
In Python 3.6, the new random.choices() function will address the problem directly:
Try
numpy.random.choice
(documentation numpy-v1.13):