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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

17 lines
Python 3.9+
import 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

stdout
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

  1. Use `numpy.random.seed()` for NumPy-based random generation.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.