3

How would I have a single line of code generate more than one random choice from a chosen list?

btw I do have import random at the top of the code

here is my code:

(R[0] = "RED", O[0] = "ORANGE", etc.)

ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = random.choice(ColourList)
print(ColourSeq)

I know at the moment I have only asked it to give me one output, but I would like it to be able to give me four of the items from ColourList in just one line of code. There can be duplicate outputs.

4 Answers 4

2

You can use random.choices instead of random.choice. It is new in version 3.6.

ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = random.choices(ColourList, k=6)
print(ColourSeq)
Sign up to request clarification or add additional context in comments.

1 Comment

nice.. i didn't knew about random.choices.. i guess i should delete my answer now :p
2

If you want to allow duplicate values, you can't use random.sample(). You can use a list comprehension:

ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = [random.choice(ColourList) for x in range(4)]
print(ColourSeq)

If you want to print those values on separate lines, without the various additions of the list, replace the print statement with

print(*ColourSeq, sep='\n')

or with the longer but clearer

for v in ColourSeq:
    print(v)

If you want them printed on the same line but with the list stuff removed, just use the simple

print(*ColourSeq)

2 Comments

Is there a way to remove the quotation marks, commas and square brackets from the answer? @RoryDaulton
@matt6297: Do my additions answer the question in your comment?
1

You can use list comprehension:

import random
ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
new_colors = [random.choice(ColourList) for i in range(4)]

Comments

0

you can use this

size = 2  
colors = random.sample(ColourList, size)

1 Comment

random.sample samples without replacement. OP needs sampling with replacement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.