I am trying to make a function that randomly selects items from a list and makes a new list with a random order of items every time it runs. I believe I have the bulk of it done, however, I am missing a way to make sure that when my function runs, it always generates just one of each item in the list without duplicates (excluding the intentional duplicates I made in my list, ie: I want a list of 16 items with 2 c1, c2, c3, etc but not something like 3 c1, 1 c2, 5 c3).
def random_assignment(): list_of_pairs = [c1, c1, c2, c2, c3, c3, c4, c4, c5, c5, c6, c6, c7, c7, c8, c8] random_list = list(random.choice(list_of_pairs)) keep_generating = True while keep_generating: return random_list if len(random_list) == 16: keep_generating = False
You can use the shuffle function from the random module like this to get a unique set of random integers:
import random my_list = list(xrange(1,100)) # list of integers from 1 to 99 # adjust this boundaries to fit your needs random.shuffle(my_list) print my_list # <- List of unique random numbers
Note here that the shuffle method doesn't return any list as one may expect, it only shuffle the list passed by reference.
No need for all of that code Python can already do that for you!!
First make a copy of your original list:
random_list = list_of_pairs
Next use the
shuffle function from the
random module which you imported:
You will now have a random list of all the elements of the original list: