The random.seed()
function in Python is used to initialize the random number generator. By setting a seed, you ensure that the sequence of random numbers generated is reproducible. Here’s a step-by-step guide to understanding and using random.seed()
:
1. Importing the random
Module
First, you need to import the random
module.
import random
2. Using random. seed()
The random. seed()
function takes an integer or a float as an argument. This value is used to seed the random number generator.
random.seed(42)
3. Generating Random Numbers
Once the seed is set, you can generate random numbers. The sequence of random numbers will be the same every time you run the script with the same seed.
print(random.random()) # Generates a random float between 0.0 and 1.0
print(random.randint(1, 10)) # Generates a random integer between 1 and 10
4. Example of Reproducibility
To see the effect of setting a seed, run the following code multiple times.
import random
random.seed(42)
print(random.random()) # Always prints the same number
print(random.randint(1, 10)) # Always prints the same number
5. Without a Seed
If you do not set a seed, the random number generator initializes the current system time or another entropy source.
print(random.random()) # Different output each time you run the script
6. Practical Applications
Setting a seed is useful in scenarios where you need reproducibility, such as:
- Testing: Ensuring that tests produce the same results every time they are run.
- Debugging: Reproducing bugs that involve random number generation.
- Research: Reproducing experiments that involve randomness.
7. Example: Reproducible Shuffling
Here’s an example of shuffling a list with and without setting a seed.
import random
# Without seed
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output varies
# With seed
random.seed(42)
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Always prints the same shuffled list