Random Sequence Generator in Python

I needed to generate random numbers but in sequence within a certain range. For example, I could generate 10,000 numbers in the range of 1000 to 9999. Rather than generate this range in sequence, I needed to generate this sequence randomly. For this exercise, random is your friend. How did I do it? The code is as below:

from random import randrange, shuffle

randomlist = []
uniqueflag = False
total_to_generate = 40000
start_range = 10000
end_range = 99999

for i in xrange (1,total_to_generate+1):
    while not uniqueflag:
        randomnumber = randrange(start_range,end_range)
        if randomnumber not in randomlist and randomnumber not in (11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999):
            uniqueflag = True
    uniqueflag = False
for x in randomlist:
    print x

You can change total_to_generate, start_range, and end_range according to your needs. I chose to exclude 11111, 22222, and so on, because they are the easiest to guess and if you need random numbers, better to exclude them. I also chose to shuffle to add a bit more randomness.

I named the file rando.py and used it as below. Since the code prints to standard output, I chose to redirect the output to a file to save the numbers.

python rando.py > numbers.txt

Hat tip to: How do I generate random numbers in Python?; shuffling elements of a list.


One Response to Random Sequence Generator in Python

  1. Great job…
    i´ll copy to my python code library…

%d bloggers like this: