Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to disable duplicated items in random.choice

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Use this :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading