buzhidao buzhidao - 1 month ago 6
Python Question

How to choose m random numbers from a range but with no duplicate?

For example, I need to choose three numbers from

but with no duplicate, the following code can't accomplish this, I know I can do it by comparing the elements, but is there some elegant way to do so?


Most general case is: choose
random numbers from range
with no duplicate.


Use the built-in random sample:

>>> import random
>>> random.sample(range(10), 5) # take 5 random elements from range(10)
[2, 4, 1, 7, 9]