If you want the entire population within a given range, as suggested by @Ashwini, you can use random.shuffle
In case you are interested in a subset of the population, you can count on using random.sample
>>> random.sample(range(1,10),5) [3, 5, 2, 6, 7]
You can also use this to simulate random.shuffle
>>> random.sample(range(1,10),(10 - 1)) [4, 5, 9, 3, 2, 8, 6, 1, 7]
Note The advantage of using random.sample over random.shuffle is that it can work on iterators, so in
- Python 3.X you don't need to convert
range() to list - In Python 2, X you can use
xrange - The same code can work in Python 2.X and 3.X
source share