Python - random.seed( ) method
random.seed() method in Python is used to initialize the random number generator, ensuring the same random numbers on every run. By default, Python generates different numbers each time, but using .
seed
()
allows result reproducibility.
It's most commonly used in:
- Machine Learning- to ensure model consistency
- Simulations- to repeat experiments
- Game Development- for consistent gameplay mechanics during testing
- Testing- to verify output correctness
Let's understand with an example.
import random
for i in range(2):
# Generated random number will be between 1 to 1000 but different in every run.
print(random.randint(1, 1000))
for i in range(2):
# Any number can be used in place of '0'.
random.seed(0)
# Generated random number will be between 1 to 1000 but same in every run.
print(random.randint(1, 1000))
Output
21 537 865 865
Explanation: Notice that generating random numbers without using the .seed() method results in different outputs on each run, whereas using it ensures consistent results every time.
Syntax
random.seed(a=None, version=2)
Parameters
- a (Optional): it's the seed value (integer, float, str, bytes, or bytearray). If None, the system time is used.
- version(Optional): defaults value is 2, using a more advanced seeding algorithm. version=1 uses an older method.
Return Type
random.seed() method does not return any value.
Let's look at some of the examples.
Reproducing Same Random Lists
We can produce the same random list for multiple executions using random.seed() method.
import random
random.seed(9)
print(random.sample(range(1, 50), 6))
Output
[30, 40, 24, 18, 9, 12]
Explanation:
- random.seed(9) sets the seed value to 9. It ensures that random values generated are same for every run.
- random.sample(range(1,50), 6) creates a sequence of numbers from 1 to 49 and randomly selects 6 unique numbers from it.
Reproducible Data Splitting
In machine learning, we often split data into training and testing sets. Using a seed ensures that the split remains the same across multiple runs.
import random
a = list(range(10)) # Sample dataset
random.seed(10)
random.shuffle(a)
print(a) # The order will always be the same when using seed
Output
[5, 2, 7, 1, 8, 4, 3, 6, 0, 9]
Explanation:
- list(range(10) gives us a list of integers from 0 to 9.
- random.seed(10) sets the seed to 10 ensuring consistant results in each run.
- random.shuffle(a) shuffles the list 'a' randomly but because of the seed() method we get the same shuffled list every time.