I’m surprised I haven’t found a way to do this without a loop, since it seems like a pretty standard problem.
Working in python,
I have colors = ["red","green","blue"] and I’d like to put these elements into a list of length N in a random order. Right now I’m using:
import random
colors = ["red","green","blue"]
otherList = []
for i in range (10): # N=10
otherList.append(random.choice(colors))
This returns: otherList = ["red","green","green","green","blue","green","red","green","green","blue"], which is exactly what I want. I’m just looking for a more idiomatic way of doing this? Any ideas? It looked like random.sample might have been the answer, but I didn’t see anything in the documentation that fit exactly my needs.
You can use a list comprehension:
Or
random.sample()through some gymnastics:Although I don’t think that is better than the list-comprehension …