-2

I have one list consisting of 10 questions. How do I choose 5 (max) at random and there can be no doubles - in python.

I have tried using:

from random import choice

strings = ['aa','bb','cc','dd','ee']
print(choice(strings))

But have no Idea how to choose 5 and have no doubles.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [How do I create a list of random numbers without duplicates?](https://stackoverflow.com/questions/9755538/how-do-i-create-a-list-of-random-numbers-without-duplicates) – mkrieger1 May 05 '22 at 20:20

2 Answers2

2

The method random.choice() draws samples with replacement. What you want is drawing samples without replacment. This is what random.sample() does.

Example with 5 samples drawn:

print(random.sample(strings, 5))

See the documentation.

ypnos
  • 50,202
  • 14
  • 95
  • 141
  • I believe this is exactly the same as my answer – D.Manasreh May 05 '22 at 20:09
  • 1
    I believe we wrote our answers at the same time then. – ypnos May 05 '22 at 20:10
  • 2
    I believe mine was first (1 min earlier to be exact). Its ok anyway. – D.Manasreh May 05 '22 at 20:10
  • "The method random.choice() draws samples with replacement." - It also draws samples *without* replacement. – Kelly Bundy May 05 '22 at 20:17
  • I certainly took more than a minute to compose my answer. @KellyBundy Maybe you are talking about numpy.random.choice? – ypnos May 05 '22 at 20:18
  • No I'm not. But *you* are probably talking about random.choices(). – Kelly Bundy May 05 '22 at 20:19
  • I'm talking about calling random.choice() multiple times which, being stateless, always leads to replacement. – ypnos May 05 '22 at 20:21
  • That involves other code, though, not just "the method random.choice". That other code is to "blame" then. If I likewise call random.sample multiple times, that can likewise lead to duplicates. – Kelly Bundy May 05 '22 at 20:25
  • I stand by my explanation as an accurate description of the matter from the point-of-view of how these two methods are applied (ie, their intended use). I also believe their wording is carefully chosen to reflect this distinction. – ypnos May 05 '22 at 20:31
1

This should work:

import random
random.sample(strings, 5)
D.Manasreh
  • 900
  • 1
  • 5
  • 9