Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

choosing non-equal random integers from an array (python)

I'm very new to python. I need to pull 5 random numbers between 1 and 100. However, these five numbers cannot be the same. I was thinking about creating a vector (range (1, 101)) and pulling random values from the vector, and then creating an loop that says if the second draw is equal to the first then draw another random number and if the draw after that is equal to the previous two draw again, etc. until 5 non-equal random numbers are pulled. Is there a more elegant way to do this?

like image 276
user3000626 Avatar asked Feb 15 '23 15:02

user3000626


1 Answers

Use random.sample:

>>> from random import sample
>>> sample(range(1, 101), 5)
[86, 90, 20, 72, 49]
like image 128
aIKid Avatar answered Feb 23 '23 15:02

aIKid