Python - Random
Overview
Estimated time: 20–30 minutes
The random
module provides pseudo-random numbers for simulations and sampling. Learn the core APIs, reproducibility with seeds, and when to use secrets
instead.
Learning Objectives
- Generate random numbers, choices, and shuffles.
- Use
random.Random()
instances for isolated RNG streams and reproducibility. - Understand the difference between
random
(PRNG) andsecrets
(crypto-grade).
Prerequisites
- Basic Python lists and numbers
Examples
import random
random.seed(42) # global seed
print(random.random()) # float in [0.0, 1.0)
print(random.randint(1, 6)) # inclusive
print(random.choice(['a','b','c']))
print(random.sample(range(10), k=3))
# Independent RNG instance
rng = random.Random(123)
print(rng.random())
items = [1,2,3,4]
random.shuffle(items)
print(items)
Expected Output (deterministic with seed): values will be stable for given seeds.
Common Pitfalls
- Security: do not use
random
for tokens/keys; usesecrets.token_hex
, etc. - Seeding the global generator affects all users of
random
in your process; prefer per-instance RNGs in libraries. - Shuffling in place mutates the list; copy first if you need the original.
Best Practices
- Use
random.Random(seed)
for reproducible experiments and tests. - Document seeds alongside results to enable reproducibility.
- Use
secrets
for any security-relevant randomness.
Checks for Understanding
- How to get a reproducible random sample of 5 integers in [0, 99]?
- Which module should you use to generate a secure token for a password reset link?
Show answers
rng = random.Random(2024); rng.sample(range(100), k=5)
secrets
, e.g.,secrets.token_urlsafe()
Exercises
- Simulate rolling two dice 10,000 times and estimate the probability distribution.
- Write a function that returns a shuffled copy of a list without mutating the original.