2

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']
Ali FGT
  • 55
  • 8

3 Answers3

5

Use this :

from random import sample
mylist = ['python', 'c++', 'html', 'CSS', 'JavaScript']
print(sample(mylist, k=4))
  • 4
    This is the only correct answer, though it lacks details. The difference between `random.sample` and `random.choice` is that `sample` is guaranteed to sample _unique_ elements which `choice` samples with replacement. – erip Jan 03 '22 at 12:53
  • 1
    While this code may answer the question, it would be better to include some context, explaining _how_ it works and _when_ to use it. Code-only answers are not useful in the long run. – martineau Jan 03 '22 at 13:29
1

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))
}
Makore
  • 88
  • 6
0

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.

Aaseer
  • 117
  • 10
  • 1
    If you convert the choices to a set, you're not guaranteed to get as many samples as you want. – erip Jan 03 '22 at 12:53