How to disable duplicated items in random.choice

Viewed 640

I want to grab a random items in a list using random.choices(), but I don't need to grab some multiple items. Example:

import random
mylist = ['python', 'c++', 'html', 'CSS', 'JavaScript']
print(random.choices(mylist, k=4)

in sometimes it returns this output:

['python', 'html', 'JavaScript', 'JavaScript']

So I want to remove the duplicated JavaScript, so it remains only one JavaScript and replace the duplicated one with a new item

['python', 'html', 'CSS', 'JavaScript']
3 Answers

Use this :

from random import sample
mylist = ['python', 'c++', 'html', 'CSS', 'JavaScript']
print(sample(mylist, k=4))

You should use a Set list for this implementation. A Set list allows you to store any type of info, but it doesn't allow you to have duplicate values.

See how Set works here.

If you want a determined number of samples, then you should make a loop where list size must reach to the number of samples wanted.

import Random

myset ={}
nSamples = 3
a =['pear','orange','cherry','pineapple','banana']
while(len(myset) != 3){
myset.add(Random.choices(a,k=1))
}

You can convert that list to a set so no doubles will happen. Even if you give doubles in the list, the set will only have singles

import random
mylist = ['python', 'c++', 'html', 'CSS', 'JavaScript']
my_set = set(random.choices(mylist, k=4))
print(my_set)

you can later convert the set to a list again.

Related