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?
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']
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.
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))
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.
import random
colours = ["R", "G", "B", "Y"] # The list of colours to choose from
output_Colours = [] # A empty list to append results to
Number_Of_Letters = 4 # Allows the code to easily be updated
for i in range(Number_Of_Letters): # A loop to repeat the generation of colour
output_Colours.append(random.sample(colours,1)) # append and generate a colour from the list
print (output_Colours)