4

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Aside: `[i for i in glob.glob("*.jpg")]` is the same as `glob.glob("*.jpg")`. Unless you're processing the filenames, there's no need for a listcomp here. – DSM Jun 06 '14 at 17:24
  • You may want to look at [this answer](http://stackoverflow.com/a/13628808/1066336). – Ralf Haring Jun 06 '14 at 17:27
  • Does this answer your question? [Pick N distinct items at random from sequence of unknown length, in only one iteration](https://stackoverflow.com/questions/9690009/pick-n-distinct-items-at-random-from-sequence-of-unknown-length-in-only-one-ite) – Mr. T Jan 06 '21 at 02:03

1 Answers1

6

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143