How do you create a randomly generated list of items while ensuring there are no duplicates?

937 views python-3.x

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

answered question

so how does this list look in the end?

The end two lines are unrechable statements.

3 Answers


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
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.

posted this

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: random_list!

posted this

from random import randint

def rand_list(length)
    lista = set()
    while len(lista) != length:

    return list(lista)

outa = rand_list(16)

posted this

Have an answer?


Please login first before posting an answer.