Reputation:
I have tried to generate random codes and tried both
sample([0..9],x)
And
[randint(0,9) for i in range(x)]
When I first used sample I noticed that it doesn't generate numbers like "2222222" it generate more distributed numbers While randint is more likely to generate numbers like "2222222".
What's the difference between both? and how I can choose the best method to generate random numbers for different cases?
Upvotes: 0
Views: 244
Reputation: 6298
sample
methodDocs describe this function:
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
In our case, the method takes x
unique elements from the given range (this is enough for the uniqueness of result), nonetheless, the range contains 10 different numbers - therefore you haven't seen repeating elements.
Note: A good question would be what happens if we pass sample population that is smaller than the amount of different elements requested.
Well, in this case, an error will raise ValueError: Sample larger than population or is negative
.
randint
LoopThe [randint(0,9) for i in range(x)]
generates random numbers, each iteration of the loop independently, so you witnessed repeating elements in the result.
Upvotes: 0
Reputation:
random.sample(x, num)
always returns num
unique element from a list x without repeating the output.
random.randint(x, y)
returns a random number in the range x and y such that x < num < y.
You can read about them here
Upvotes: 0