How to Reset Python's Random Seed for Deterministic Output
This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.
Python code
17 linesimport random
def seeded_random_sequence(seed, count=5, low=1, high=100):
random.seed(seed)
return [random.randint(low, high) for _ in range(count)]
if __name__ == "__main__":
seed_value = 42
first_run = seeded_random_sequence(seed_value)
print("First run:", first_run)
# Reset seed and generate again to show determinism
second_run = seeded_random_sequence(seed_value)
print("Second run:", second_run)
# Verify they match
print("Deterministic:", first_run == second_run)
Output
First run: [81, 14, 3, 94, 35]
Second run: [81, 14, 3, 94, 35]
Deterministic: True
How it works
Calling random.seed(seed) initializes the internal state of the Mersenne Twister used by Python's random module. By reseeding with the same value before each sequence generation, every call to random.randint follows the same pseudo-random number sequence. This is essential for making experiments or simulations reproducible. The seed value can be any hashable object, but integers are most commonly used.
Common mistakes
- Forgetting to reseed before each generation, leading to different results.
- Using `random.seed()` inside a loop, which can reset the sequence unintentionally.
- Assuming the same seed always produces the same output across different Python versions or platforms.
Variations
- Use `numpy.random.seed()` for NumPy-based random generation.
- Use `secrets` module for cryptographic randomness where determinism is not desired.
Real-world use cases
- Reproducing machine learning experiments by fixing random seeds for data shuffling and model initialization.
- Creating deterministic game levels or procedural content generation for testing and consistent player experiences.
- Running A/B tests where identical random assignment of users to groups must be replicable for auditing and debugging.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.