This article demonstrates how to use the random.seed()
function to initialize the pseudo-random number generator in Python to get the deterministic random data you want.
Table of contents
- What is a seed in a random generator?
- Why and When to use the seed() function
- How to use random.seed() function
- Set system time as a seed value instead of OS-specific randomness source
- Get a seed value used by a random generator
- Python random seed with randrange
- Use the Random seed and choice method together
- Use random seed and sample function together
- Use random seed and shuffle function together
- Next Steps
What is a seed in a random generator?
The seed value is a base value used by a pseudo-random generator to produce random numbers. The random number or data generated by Python’s random module is not truly random; it is pseudo-random(it is PRNG), i.e., deterministic. The random module uses the seed value as a base to generate a random number.
Use a random.seed()
function with other random module functions to reproduce their output again and again.
Why and When to use the seed() function
Random module’s seed()
function particularly useful in programming contexts where you want the same sequence of random numbers to be generated each time the code is run, such as in simulations, testing, and data science.
Also, the random.seed()
is useful to reproduce the data given by a pseudo-random number generator. By re-using a seed value, we can regenerate the same data multiple times as multiple threads are not running.
For example:
- We can choose the same elements from the list randomly every time using
random.seed()
. - Always produces the same random number
- Shuffles the list in the same way to produce the same sequence of elements
Also, the seed value is very significant in computer security to pseudo-randomly generate a secure secret encryption key. So using a custom seed value, you can initialize the robust and reliable pseudo-random number generator the way you want.
When we supply a specific seed to the random generator, you will get the same numbers every time you execute a program. That is useful when you need a predictable source of random numbers.
How to use random.seed() function
Let’s understand the working of a seed()
function.
Syntax of random.seed()
random.seed(a=None, version=2)
Code language: Python (python)
It initialize the pseudo-random number generator with seed value a
.
Parameters: –
It accepts two parameters. Both are optional.
a
: It is the seed value. If the a is None, then by default, current system time is used.
If the operating system provides randomness sources, they are used instead of the system time. For example, On windows, theos.urandom()
internally usesCryptGenRandom()
to generate random data.
If you pass a seed value in the form of an integer, it is used as it is.version
: If the version is set to 2 by default,str
,bytes
, orbytearray
object gets converted to anint
, and all of its bits are used.
When we say OS-specific randomness source it means: –
- On Linux, the
getrandom()
function can be used to get random bytes in non-blocking mode - On a Unix-like system, random bytes are read from the
/dev/urandom
device - On Windows, it will use
CryptGenRandom()
.
Important points:
- If you don’t initialize the pseudo-random number generator, then the random generator uses the OS’s randomness sources to set the seed value. That’s why whenever we execute the
random.random()
, we get a different number. - When Python failed to get the OS-specific randomness source then by-default current system time is used as a seed value.
random seed() example to generate the same random number every time
If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function. It means any subsequent random operations will produce the same results each time the script is run with the same seed.
Example 1:
Output:
Random number with seed 30 42 42 42
As we can see in the output, we got the same number three times because we seeded them with the same value before calling a random.randint()
.
Example 2: Using seed for different purpose.
Output:
Random number with seed 30
Run 0 :
0 : 42
1 : 50
2 : 34
Run 1 :
0 : 42
1 : 50
2 : 34
Example 3: shuffles the list in the same way with seed 30.
This is useful in producing the sequence of elements with seed 30.
Output:
[20, 10, 40, 30, 50]
[20, 10, 40, 30, 50]
Another Example
Suppose you call a random.randint() twice before calling a seed()
you will get a different number. If you want different data, then pass the different seed value before calling any other random module function.
Example
Output:
first Number 42 Second Number 50 Third Number 42
We got a different number in the second place in the output because we executed randint()
twice without setting the seed value.
Note: Setting the seed affects all subsequent calls to random number generation functions in the random module. If you need randomness that is not reproducible, simply do not set the seed or change it.
You can also use the getstate() and setstate() functions, which help us to capture the current internal state of the random generator.
Capture and store the current state using a random.getstate()
. Next, whenever you want the same result change the current state of the random number using the random.setstate(state).
By changing the current state to the previous state we can get the same random data again
Set system time as a seed value instead of OS-specific randomness source
For any reason, if you want to set a custom seed other than an OS-specific randomness source, a common practice is to use system time in milliseconds as a seed value.
Get a seed value used by a random generator
Sometimes it is useful to be able to reproduce the data given by a pseudo-random number generator. As you already know, random data generation is dependent on a seed value. By re-using a seed value, we can regenerate the same data multiple times as multiple threads are not running.
For example, You want to reproduce the results you are getting in a particular run. In such cases, you want to know the seed used to replicate that result. The current seed value is essential when you want reproducible results.
Using a custom seed value, you must remember that Python’s Random generator doesn’t store seed in memory. i.e., It doesn’t provide any method to get the current seed value. It is up to you to save the seed if you want to reuse it. It is not possible to get the automatic seed back out from the generator. But you can try this alternative.
The above way is time-based, so each time you execute it, it will produce a different seed, and if you like the result, you can use that seed to get the same result back.
Now, I will use the same seed (7616533358804326209) to get the same result back.
Note: Using the above approach you can reproduce the result of any random module function
Python random seed with randrange
Let see how to use seed()
function to get the same random number within a given range.
Use the Random seed and choice method together
The random choice() function is used to choose a random element from the list and set. By setting the custom seed value, you can pick the same choice every time.
Use random seed and sample function together
Using a random sample() function, we can select random samples from the list and other sequence types. Let’s see how to get the same random samples out of the list every time using a seed()
and sample()
function.
Use random seed and shuffle function together
We can also use the seed()
and random.shuffle() functions together. The primary purpose of using the seed()
and shuffle()
function together is to produce the same result every time after each shuffle. If we set the same seed value every time before calling the shuffle()
function, we will get the same item sequence. I.e., shuffling produces the same result every time.
Example: –
Next Steps
Let me know your comments and feedback in the section below.
Also, try to solve the following Free exercise and quiz to have a better understanding of working with random data in Python.