Select a non-repeating random item from the 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 the list. My problem is that it is not unique, and many photos are repeated. Is there any way to overcome this?

+4
source share
1 answer

Use random.sampleto select random non-repeating elements:

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

random.samplereturns an object list.

Side note: there is no need to understand the list if you do not plan to filter the result glob.glob.

+6
source

Source: https://habr.com/ru/post/1543597/


All Articles