72

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?

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
kev xlre
  • 721
  • 1
  • 5
  • 3
  • Related: Without replacement(keep order: https://stackoverflow.com/questions/6482889/get-random-sample-from-list-while-maintaining-ordering-of-items ; without keep order (normal): https://stackoverflow.com/questions/22741319/what-does-random-sample-method-in-python-do, weighted: https://stackoverflow.com/questions/43549515/weighted-random-sample-without-replacement-in-python) – user202729 Dec 30 '21 at 03:51

4 Answers4

80

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']
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
23

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))
normanius
  • 8,629
  • 7
  • 53
  • 83
Priyank
  • 1,513
  • 1
  • 18
  • 36
23

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
1

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)
CodeCupboard
  • 1,507
  • 3
  • 17
  • 26