Generate 'n' unique random numbers within a range


I know how to generate a random number within a range in Python.

random.randint(numLow, numHigh)

And I know I can put this in a loop to generate n amount of these numbers

for x in range (0, n):
    listOfNumbers.append(random.randint(numLow, numHigh))

However, I need to make sure each number in that list is unique. Other than a load of conditional statements, is there a straightforward way of generating n number of unique random numbers?

The important thing is that each number in the list is different to the others..


[12, 5, 6, 1] = good


[12, 5, 5, 1] = bad, because the number 5 occurs twice.

This question is tagged with python random unique

~ Asked on 2014-04-03 15:29:57

The Best Answer is


If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
Sample size exceeded population size

~ Answered on 2014-04-03 15:34:45


Generate the range of data first and then shuffle it like this

import random
data = range(numLow, numHigh)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

But you can use random.sample to get the number of elements you need, from a range of numbers like this

print random.sample(range(numLow, numHigh), 3)

~ Answered on 2014-04-03 15:31:46

Most Viewed Questions: