0

If I have a list of 10 items like ["item1", "item2", "item3", ..., "item10"]

random.sample(range(10), 4)

would return a list of 4 unique items within the range.

Is there another "random" method that returns a random list with the possibility of repeating items?

jpp
  • 159,742
  • 34
  • 281
  • 339
Aadil
  • 19
  • 7

1 Answers1

1

There isn't a trivial function (like sample) for sampling with replacement because it's so trivial you really don't need one:

[random.choice(range(10)) for _ in range(4)]

There is a function for less-trivial uses of sampling with replacement, choices. And you can call it with no weights or anything else if you want:

random.choices(range(10), k=4)

But it's not really any easier to understand.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • There is [`random.choices`](https://docs.python.org/3/library/random.html#random.choices) nowadays :) – miradulo Mar 26 '18 at 00:46
  • @miradulo I was editing that into th question, trying to figure out how to should explain that it adds a 3.6 dependency that you probably don't need and requires using a keyword argument, and then decided to strip all of that out… – abarnert Mar 26 '18 at 00:48
  • Sure, to each their own I suppose - I find it trivial enough. – miradulo Mar 26 '18 at 00:55
  • Thank you this code: [random.choice(range(10)) for _ in range(4)] did the job. I have python 2.7, so random.choices wouldn't work – Aadil Mar 26 '18 at 01:01
  • @miradulo Looks like the 3.6 dependency turned out to be relevant after all. (It's always hard to guess with minimalist questions…) – abarnert Mar 26 '18 at 01:03