Playground / random.seed and the Mersenne Twister

Same seed, same 'random' numbers

random.seed and the Mersenne Twister

Interactive lab

Try it: random.seed and the Mersenne Twister

Python's random module is a deterministic generator: random.seed(n) sets the Mersenne Twister's internal state, and every random(), randint(), choice() and shuffle() consumes 32-bit outputs from it in order — so the same seed replays the same sequence and a different seed gives a different one.

How it works

  1. random.seed(n) splits |n| into 32-bit words and runs MT19937's init_by_array, filling the 624-word state.
  2. Each 32-bit output takes the next state word and tempers it; after 624 words the whole state is regenerated (the twist).
  3. random() joins two outputs: (a·2^26 + b) / 2^53 with a = word >> 5, b = word >> 6, a float in [0.0, 1.0).
  4. randint(a, b) = a + _randbelow(b − a + 1); choice(seq) = seq[_randbelow(len(seq))]; _randbelow(n) keeps the top n.bit_length() bits and rejects values ≥ n.
  5. shuffle walks i from the end down to 1 and swaps x[i] with x[_randbelow(i + 1)].
  6. Replaying the program with a second seed shows where the sequences agree or first diverge.

Default run (11 steps): A program of 5 random-module calls, run after random.seed(42). … Replay with random.seed(42): every result is identical — same seed, same state, same sequence.

Simplified: Seeds are non-negative integers below 2^32 (one key word), at most 8 calls, randint bounds within ±1000, and lists of up to 8 simple items. Only mt[0..3] and mt[623] of the 624-word state vector are shown (abbreviated). Everything else follows CPython 3.12's random module exactly.

Educational simulation

Loading the simulation…