ubuntuaskdanidani ubuntuaskdanidani - 10 months ago 48
Python Question

Choose a non-repeating random element from a list using Python

I have this list:

pics = [i for i in glob.glob("*.jpg")]
choice = random.choice(pics)

and the code below the list was used to select a random image from a list. My problem is that it isn't unique and lots of pictures repeat.. Is there any way to overcome that?


Use random.sample to choose random non-repeating elements:

>>> import random
>>> random.sample(glob.glob('*.jpg'), number_of_images_to_choose)

random.sample returns a list object.

Side note: there's no need in list comprehension, unless you're planning to filter the result of glob.glob.