Python Random Seed Method to Repeat Same Random Value

This tutorial guides you on using the random module’s seed() method. You would know how to call seed() function to initialize the pseudo-random number generator (PRNG) in Python.

PRNG means that it can generate a number that seems to be random and also usable by many applications. But in reality, they are not more than a randomized but predictable sequence of values.

It also indicates that you should not apply them to applications which involves encryption and perform crypto operations. There are ways in Python to generate secure random generators, check the post below.

Must Read – Generate Random Numbers in Python

Seed() to Initialize Generator and Repeat the Same Number

In this tutorial, our focus is on the Python random module’s seed() method. How can you use it to initialize a random number generator? And able to produce the exact similar random number.

How to call random.seed() function

We’ve summarized some of the keynotes before we move on to using the random module and the seed method.

Python generates pseudo-random numbers which are not entirely random instead are deterministic in nature. Their source is some initial value fed to the process. We call it a seed value. Hence, the output of the Python random module derives from the seed data.

The word “deterministic” means here that it is possible to pre-determine a value.

Usually, the programmers take the generator’s first output as the seed value. By the way, when you begin to invoke the generator, it doesn’t have any previous data. In this case, the system time acts as the initializer.

By customizing seed value, we can set up the pseudo-random number generator (PRNG) as per our requirement. Now, let’s see what to do to use the random.seed() method.

random.seed() signature

The seed function can take two optional arguments.

random.seed(value=None, version=2)
  • The first argument represents the seed data which is by default None. It means system time works as the seed. If it is a valid integer value, then it gets used as is.
  • The second argument is the version and has two as default. It specifies that any string, bytes or array and all that turn into a number (int).

Things to know about the seed value

The Random Module considers the seed value as a base to produce a random number. If seed data is not available, then it uses the system time.

If you didn’t call the random seed() method, then every time you call the generator, it sets the current system time as the seed data.

It is the main reason that subsequent calls to random.random() always return a different number.

The seed value plays a critical role when generating cryptographically secure random numbers.

Code to generate the same random value using  seed()

This example gives you an idea to utilize the seed() function to produce a deterministic random data. If you want to create the same value in each call to a generator, then keep the seed value same before using a module method.

Below example will make it more clear for you.

from random import *

def main():
    # if you like to regenerate a random value,
    # then keep the same seed data for every operation
    myseed = 10
    print("Seed data for generator: {}".format(myseed))

    # See the fixed seed value
    seed( myseed )

    # Generate our first random number
    print("#1 - {}".format(randint(1, 20))) 

    # Keep the seed value constant
    seed( myseed )

    # Generate the second random number
    print("#2 - {}".format(randint(1, 20)))

    # Don't change the seed value
    seed( myseed )

    # Generate the third random number
    print("#3 - {}".format(randint(1, 20)))

main()

Output

Seed data for generator: 10
#1 - 19
#2 - 19
#3 - 19

It is clear from the summary that the outcome of each generator call is the same number. No surprise, it is because we kept the seed value constant for every call to random.randint().

Note: If you miss the seed call before calling randint(), then you will get the different output.

It also means that if you want a distinct output, then set different seed values before calling a random module method.

Check out this example.

from random import *

def main():
    # if you like to regenerate a random value,
    # then keep the same seed data for every operation
    myseed = 10
    print("Seed data for generator: {}".format(myseed))

    # See the fixed seed value
    seed( myseed )

    # Generate our first random number
    print("#1 - {}".format(randint(1, 20))) 

    # Seed call missed in between
    # seed( myseed )

    # Generate the second random number
    print("#2 - {}".format(randint(1, 20)))

    # Don't change the seed value
    seed( myseed )

    # Generate the third random number
    print("#3 - {}".format(randint(1, 20)))

main()

Output

Seed data for generator: 10
#1 - 19
#2 - 2
#3 - 19

In this second example, you can observe that we intentionally missed the seed call in the second iteration and hence the subsequent randint() gave a different random number. In the other two operations, the output was the same.

Random seed with randrange in Python

In this section, we’ll see how to get the seed() method working for values in a given range.

from random import *

def main():
    # if you like to regenerate a random value,
    # then keep the same seed data for every operation
    myseed = 555

    seed(myseed)
    print ("#1 Random number between given range - ", randrange(111,999))

    seed(myseed)
    print ("#2 Random number between given range - ", randrange(111,999))

    seed(myseed)
    print ("#3 Random number between given range - ", randrange(111,999))

main()

Output

#1 Random number between given range -  308
#2 Random number between given range -  308
#3 Random number between given range -  308

Seed to initialize with the choice method

Python choice() function picks a random element from any sequence such as a list or a set.

If we want to keep the same choice in every iteration, then we can integrate seed with the choice method to accomplish this.

Check out how the two methods work with each other.

from random import *

def main():
    # if you like to regenerate a random value,
    # then keep the same seed data for every operation
    myseed = 6

    seq = [1111, 2222, 3333, 4444, 5555, 6666]

    seed(myseed)
    randomVal = choice(seq)
    print ("#1 Random item from seq: ", randomVal)

    seed(myseed)
    randomVal = choice(seq)
    print ("#2 Random item from seq: ", randomVal)

    seed(myseed)
    randomVal = choice(seq)

main()

Output

#1 Random item from seq:  5555
#2 Random item from seq:  5555

Calculate seed and generate a random number

In most cases, we want to control the random number and choose it. We need such a thing for producing similar results.

PRNG in Python is dependent on the seed value to generate a random value.

Hence, if the seed of a number is already available, then you can produce the same random number in every operation.

How to determine the seed of a number?

Say, you have a number M, and its seed is N. To calculate N, you need to multiple M with the product of each digit in M.

M = 22
N = 22 * 2 * 2 = 88

Now, we have provided an example to demonstrate how to decide the right seed for random number generation. Below is the sample code that finds out the seed value of a number.

Example

"""
Date Time
@Python 3.5

Get all possible seed for a given number.
Eg : 24 = 12 * 1 * 2 = 24 so 12 is the seed of 24.
"""

def findSeed(num):
    product = 1
    seed = 1

    while (seed <= (num * 0.5)):
        if (num % seed == 0):
            factor = seed
            product = factor
            while (not(factor == 0)):
                mod = factor % 10
                factor = factor // 10
                product *= mod
            if (product == num):
                print("The seed of {} is: {}".format(num, seed))
        seed += 1

findSeed(24)
findSeed(1716)

Output

The seed of 24 is: 12
The seed of 1716 is: 143

Integrate random seed with sample() method

You can club the seed with the sample function and generate random numbers.

The sample() method allows generating the same random values from a sequence and other types.

You can generate the same random values from the sequence every time. It requires setting the same seed value before calling the sample().

Check out the two functions work together:

import random
#clubbing random.seed() and random.sample()
seq = ["C++", "C#", "Python", "R", "Kotlin", "Go", "Scala", "PHP", "JavaScript"]
random.seed(5)
eg_list = random.sample(seq, 5)
print("#1 Sample language list ", eg_list)
random.seed(5)
eg_list = random.sample(seq, 5)
print("#2 Sample language list ", eg_list)
random.seed(5)
eg_list = random.sample(seq, 5)
print("#3 Sample language list ", eg_list)

Output

#1 Sample language list  ['Kotlin', 'Go', 'Scala', 'PHP', 'JavaScript']
#2 Sample language list  ['Kotlin', 'Go', 'Scala', 'PHP', 'JavaScript']
#3 Sample language list  ['Kotlin', 'Go', 'Scala', 'PHP', 'JavaScript']

Integrate random seed with shuffle() method

You can club the seed with the shuffle function and generate random numbers.

The shuffle() and seed() together allows generating same random values from a sequence.

If you provide the same seed data every time before invoking the shuffle function, then it’ll get you the same number sequence. Hence, it is possible to shuffle a series with a parameter so that the system provides the same output again and again.

Check out the two functions work together:

import random
num_list = [11, 22, 44, 55, 66, 77, 88, 99]
print ("Before shuffling: ", num_list )
random.seed(5)
random.shuffle(num_list)
print("After shuffling: ", num_list)
num_list = [11, 22, 44, 55, 66, 77, 88, 99]
random.seed(5)
random.shuffle(num_list)
print("After re-shuffling: ", num_list)

Output

Before shuffling:  [11, 22, 44, 55, 66, 77, 88, 99]
After shuffling:  [88, 55, 22, 11, 99, 44, 77, 66]
After re-shuffling:  [88, 55, 22, 11, 99, 44, 77, 66]