Lesson · Date, Time & Numbers
Randomness
55 min readRandomness
Pseudo-random generators are reproducible tools for simulation and tests, not security. `secrets` exists for tokens, passwords, and other values that must resist prediction.
Learning goals
- Create an independent generator with
random.Random(seed)and demonstrate that runs repeat. - Explain why the same seed produces the same sequence and what that means for tests.
- Draw samples with and without replacement using
sampleandchoices. - Shuffle a list in place and reproduce the order by reseeding.
- Choose
secretsoverrandomfor tokens and explain what the latter cannot guarantee.
Mental model
Two sources, two contracts: a seeded pseudo-random generator is deterministic on purpose, which makes simulations repeatable and makes security values guessable on the same terms. Pick the source from what the value must survive.
Mental model
read it top to bottom
seed 42
↓ seeds one generator's state
random.Random(42) independent and reproducible
↓ randint / sample / shuffle / choices
same seed + same calls → same outputs (tests, simulations)
secrets OS-backed randomness
(values that must stay unguessable)Core idea
The seed is the contract: seeding random.Random(42) fixes the entire sequence of values that follows, so the same seed and the same calls always replay the same run. That single property is both the feature and the risk: reproducibility is what simulations and tests need, and it is exactly what makes a value predictable to anyone who learns the seed. secrets steps outside that contract by drawing from an operating-system source that no seed can reconstruct.
random
The random module provides the Random class plus module-level functions backed by one shared default instance. Values come from a deterministic algorithm: seed the generator and the whole sequence repeats, which suits simulations, games and test data, never security tokens.
Seeds
A seed is the starting state for a pseudo-random generator's algorithm. random.Random(42) creates an independent generator from that seed, and random.seed(42) resets the shared module-level instance, so the same seed and the same calls always produce the same values. Reproducing a run and predicting a value are the same ability, which is why seeded output must never protect a secret.
Sampling
Sampling means drawing several values from a sequence at once. sample(population, k) is the without-replacement form: all k results are distinct, and asking for more values than the population holds raises ValueError. Whether a repeat is allowed decides which sampling call fits.
Shuffling
shuffle(sequence) reorders a mutable sequence in place and returns None. The new order is a deterministic function of the generator's state, so two generators with the same seed shuffle equal lists into the same order, which is how a test can replay a "random" arrangement.
Choices
choices(population, weights=None, k=1) is the with-replacement form: it returns a k-element list and the same element can appear more than once. weights biases each element's chance, so choices can model a loaded die where each face has a different probability.
Deterministic tests
Seed or inject a pseudo-random generator when a test needs repeatable random-looking data. Security tokens should not be made deterministic this way.
secrets
secrets uses an operating-system-backed source suitable for security-sensitive tokens and random choices. Do not replace it with random for authentication or reset links.
Walkthrough
random.Random(42)creates an independent generator whose state starts from seed 42; it does not touch the module-level functions such asrandom.randint, which use their own shared instance.rng.randint(1, 6)returns an integer with both endpoints included (1 and 6 are possible), and the list comprehension collects five rolls. Because the generator is seeded, running the script again replays the same five values.secrets.token_urlsafe(24)asks the operating system for random bytes and renders them as URL-safe text, so the token stays unpredictable even to someone who has watched every earlier call.- Predict before running: whether a second run of the script prints the same five rolls, and whether it prints the same token.
Experiments to try
- Run the snippet twice and compare the outputs line by line; state which line is reproducible from the seed and which one is not.
- Build two generators from seed 7, call
randint(1, 6)on each in the same order, and confirm the sequences match; then insert an extra call on one generator only and watch the sequences fall out of step. - Draw three values from
"abcdef"once withrng.sample(...)and once withrng.choices(..., k=3); run each call several times and connect the repeats, or their absence, to drawing with and without replacement. - Seed a temporary generator with a known seed and produce a fake token from it twice: both runs match. Then print
secrets.token_urlsafe(24)twice and explain why the two tokens differ.
Common mistakes
- Seeding the shared module-level instance with
random.seed(42)and assuming every laterrandomcall is yours: the instance is one hidden global, so library code that also draws from it consumes the same sequence and can shift your "reproducible" results. - Reading
rng.shuffle(deck)as returning a new list: the call reordersdeckin place and returnsNone, sodeck = rng.shuffle(deck)replaces the list withNoneand quietly loses the data. - Confusing
samplewithchoices:sampledraws without replacement, so it cannot return a repeat and raisesValueErrorwhenkexceeds the population, whilechoicesdraws with replacement and may repeat values. - Treating
randomoutput as a secret because the value "looks random": the algorithm is deterministic, so anyone who learns or guesses the seed can replay the token, reset code, or key. Security values belong tosecrets.
Practice: Easy
- Run the worked example twice; write down both outputs and state which lines stayed identical and which line changed.
- Create two generators with
random.Random(7)and callrng.randint(1, 6)three times on each in the same order; confirm the sequences match, then seed a third generator with 8 and compare. - Draw three values from
list("abcdef")once withrng.sample(letters, 3)and once withrng.choices(letters, k=3); run each several times and explain the difference in repeats.
Practice: Medium
- Write
roll_five(seed)that returns fiverandint(1, 6)rolls from a freshrandom.Random(seed); call it with seeds 1, 42 and 42 again and show that the last two calls return identical lists. - Shuffle a six-item list with
rng.shuffle, record the order, then build a freshrandom.Randomwith the same seed, copy the original list, and shuffle the copy; explain why shuffling a copy is required to reproduce the first order. - Write
token(mode)that returns asecrets.token_urlsafe(16)value when mode is "secure" and a value from a seededrandom.Randomwhen mode is "repeat"; run each mode twice and point out which mode could be predicted by an attacker.
Practice: Hard
- Simulate 1000 rounds of two dice: use
random.Random(2026)for bothrandint(1, 6)calls, count the totals 2 to 12 withcollections.Counter, and rerun with the same seed to show the histogram is identical. - Design
deal(seed, deck)that returns a shuffled copy ofdeckfor the given seed; define what happens to the input list, prove two calls with the same seed return the same order, and state in one sentence why a game is exploitable when a player can guess the seed. - Failure lab: trigger
ValueErrorby askingsamplefor more values than the population holds, show thatshufflereturnsNone, and generate a "token" from a seeded generator twice to prove it repeats; for each result, write what it demonstrates about the difference between reproducibility and security.
Lesson checklist
- I can create a seeded generator and show that two runs produce the same values.
- I can pick between
sampleandchoicesbased on whether repeats are allowed. - I can shuffle a list reproducibly and explain why the same seed replays the same order.
- I can say why a token must come from
secretsand never from a seededrandomgenerator.
Remember
A seeded generator is a replayable sequence: `random.Random(42)` fixes every value that follows, which makes simulations and tests repeatable and makes the same values predictable to anyone who knows the seed. `sample` draws without replacement, `choices` draws with it, and `shuffle` reorders a list in place. Values that must stay unguessable come from `secrets`, which cannot be seeded or replayed.
Interview angles
What is the main purpose of **random**?+
The random module supplies pseudo-random values for simulations, games and test data through the Random class and a shared module-level instance. Its output is deterministic given a seed: the same state produces the same sequence, which makes runs reproducible and rules it out for secrets.
What should you pay attention to when using **Seeds**?+
A seed fixes the generator's starting state, so the same seed and the same calls replay the same values. That is exactly what a test needs to reproduce a failing run, and exactly why a seeded value must never protect a secret.
How does **Sampling** fit into this lesson?+
Sampling draws several values at once. sample(population, k) is the without-replacement form, so no value repeats and an oversized k raises ValueError; the with-replacement form is choices, covered as its own concept.
Why can output from a seeded `random` generator not be used as a security token?+
The generator is deterministic: whoever learns or guesses the seed can replay the whole sequence and compute the same token. secrets avoids that by drawing from an operating-system source that has no seed to reconstruct.