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.

By setting the custom seed value, we can reproduce the data given by a pseudo-random number generator. Choose the same elements from the list randomly every time using `random.seed()`

## 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

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.

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.

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()`

`random.seed(a=None, version=2)`

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, the`os.urandom()`

internally uses`CryptGenRandom()`

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`

, or`bytearray`

object gets converted to an`int`

, 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. Let’s see how to set seed in Python pseudo-random number generator.

```
import random
print('Random number with seed 30')
for i in range(3):
# Random number with seed 30
random.seed(30)
print(random.randint(25, 50))
```

**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()**

Suppose you call a random.randint() twice before calling a `seed()`

you will get a different number. If If you want different data, then pass the different seed value before calling any other random module function.

**Example**

```
import random
random.seed(30)
print("first Number", random.randint(25, 50))
# generates a different random number
print("Second Number ", random.randint(25, 50))
# will generate a same random number as first one because seed value is same
random.seed(30)
print("Third Number", random.randint(25, 50))
```

**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**: 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.

```
import random
from datetime import datetime
# Random number with system time
random.seed(datetime.now())
print("Random Number", random.randint(25, 50))
# Output 50
```

## 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.

```
import random
import sys
# create a seed
seed_value = random.randrange(sys.maxsize)
# save this seed somewhere. So if you like the result you can use this seed to reproduce it
print('Seed value:', seed_value)
# Output 4542355562136458828
# Now, Seed the random number generator
random.seed(seed_value)
num = random.randint(10, 500)
print("Random Number", num)
# Output 404
```

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.

```
import random
# Seed the random number generator with your value
random.seed(4542355562136458828)
num = random.randint(10, 500)
print("Random Number", num)
# Output 404
```

**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.

```
import random
# Random seed with randrange
random.seed(350)
print(random.randrange(300, 500))
# output 336
random.seed(350)
print(random.randrange(300, 500))
# Output 336
```

## 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.

```
import random
names = ["Alex", "Emma", "Kelly", "Scott", "Jessa"]
random.seed(50)
random_item = random.choice(names)
print ("First random name from list ", random_item)
# output scott
random.seed(50)
random_item = random.choice(names)
print ("Second random name from list ", random_item)
# output Scott
```

## 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.

```
import random
# using random.seed() and random.sample() together
fruit_list = ["Apple", "Mango", "Banana", "Apricot", "Cherries", "Grape", "Kiwi"]
random.seed(3)
sample_list = random.sample(fruit_list, 3)
print("First sample fruit list ", sample_list)
# Output ['Mango', 'Cherries', 'Grape']
random.seed(3)
sample_list = random.sample(fruit_list, 3)
print("Second sample fruit list ", sample_list)
# output ['Mango', 'Cherries', 'Grape']
```

## 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**: –

```
import random
numbers = [10, 20, 30, 40, 50, 60]
print("Original list: ", numbers)
random.seed(4)
random.shuffle(numbers)
print("Shuffled list ", numbers)
# Output [40, 60, 50, 10, 30, 20]
random.seed(4)
random.shuffle(numbers)
print("Reshuffled list ", numbers)
# Output [40, 60, 50, 10, 30, 20]
```

## 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.