Topics in this subject
NumPy 1 min read Updated 4 Aug 2026

13. Random Module

Modern NumPy uses the Generator API (np.random.defaultrng), which is preferred over legacy np.random..

Modern NumPy uses the Generator API (np.random.default_rng), which is preferred over legacy np.random.*.

rng = np.random.default_rng(seed=42)   # reproducible

rng.random((2, 2))          # uniform [0,1)
rng.integers(0, 10, size=5) # random ints [0,10)
rng.normal(0, 1, size=3)    # Gaussian mean=0 std=1
rng.uniform(1, 5, size=3)   # uniform [1,5)
rng.choice([10,20,30], size=2, replace=False)
rng.binomial(n=10, p=0.5, size=3)
rng.poisson(lam=3, size=3)

arr = np.arange(5)
rng.shuffle(arr)            # in-place shuffle
rng.permutation(5)          # shuffled copy of range

Legacy (still common in tutorials):

np.random.seed(0)
np.random.rand(2, 2)    # uniform
np.random.randn(3)      # standard normal
np.random.randint(0, 10, 5)

🚀 Best Practice: Use default_rng(seed) for reproducibility and better statistical quality. Set the seed once for a reproducible pipeline.

Interview Question: rand vs randn? rand = uniform on [0,1); randn = standard normal (mean 0, std 1).