Computers can't generate truly random numbers algorithmically — np.random's functions are pseudo-random, deterministically computed from an internal state that evolves with each call. Calling np.random.seed(n) resets that internal state to a fixed, known starting point derived from n, so every subsequent random call produces the exact same sequence of values every time the program runs with that same seed — invaluable for writing reproducible tests, tutorials, and debugging, though obviously not appropriate for anything requiring genuine unpredictability, like security tokens.
1Understanding np.random.seed()
Computers can't generate truly random numbers algorithmically — np.random's functions are pseudo-random, deterministically computed from an internal state that evolves with each call. Calling np.random.seed(n) resets that internal state to a fixed, known starting point derived from n, so every subsequent random call produces the exact same sequence of values every time the program runs with that same seed — invaluable for writing reproducible tests, tutorials, and debugging, though obviously not appropriate for anything requiring genuine unpredictability, like security tokens.
Call np.random.seed() once, near the start of a script or test, rather than repeatedly before every individual random call — reseeding partway through a sequence of calls can accidentally make some of them correlated or repeat values you didn't intend.
import numpy as np
np.random.seed(42)
print(np.random.rand(3))
np.random.seed(42)
print(np.random.rand(3))2Practical Example
Here is a real-world application of np.random.seed() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(1)
first_run = np.random.randint(0, 100, 3)
np.random.seed(1)
second_run = np.random.randint(0, 100, 3)
print(np.array_equal(first_run, second_run))3Best Practices
Follow these guidelines when working with np.random.seed():
1. Set a seed once at the start of a script/test for full reproducibility, rather than seeding before every individual call
2. Never rely on np.random (seeded or not) for anything security-sensitive, like tokens or passwords — use the secrets module instead
3. Prefer the newer np.random.default_rng(seed) Generator API over the legacy global np.random.seed() in new code, since it avoids relying on shared global state
Tip: Call np.random.seed() once, near the start of a script or test, rather than repeatedly before every individual random call — reseeding partway through a sequence of calls can accidentally make some of them correlated or repeat values you didn't intend.
import numpy as np
np.random.seed(42)
print(np.random.rand(3))
np.random.seed(42)
print(np.random.rand(3))