random.getstate / setstate

seed() can only restart a sequence from the beginning; getstate()/setstate() rewind to any point. The state is the 624-word Mersenne Twister array, the position in it, and the value gauss() has cached.

random functionAll Python 3 versionsLive demo
Common call
state = random.getstate(); ...; random.setstate(state)
Returns
(3, (625 ints), gauss_next) / None
Replaces
Re-seeding and re-drawing to get back to a point
Watch out
Only valid between Random-compatible generators; SystemRandom raises
random.getstate() / random.setstate(state)
→ tuple | None

Demo

Live evaluation
Save the state, draw five numbers, restore, draw again: the same five.
Try:
Inputs
seedint | stran int or a string
Code
import random
random.seed(42)
state = random.getstate()
first = [random.randint(1, 9) for _ in range(5)]
random.setstate(state)
again = [random.randint(1, 9) for _ in range(5)]
(first, again)
Result
([2, 1, 5, 4, 4], [2, 1, 5, 4, 4])

Right after seeding the position is 624: the array is "used up", so the first draw regenerates all 624 words and resets the position to 0. Each random() consumes two 32-bit words, so after one call the position is 2, and after 313 calls (626 words) it has wrapped around once and is 2 again. state[2] is None because no gauss() value is cached.

Parameters

NameTypeRequiredDescription
statetupleyessetstate: an object returned by getstate() (version 3; version 2 tuples from old Pythons are converted).

Return value

tuple | None — getstate: (3, tuple of 625 ints, gauss_next). setstate: None.

Common patterns

Checkpoint a simulation
Save the state with your results; resume later with identical randomness.
import pickle
import random
with open('checkpoint.pkl', 'wb') as f:
    pickle.dump({'step': step, 'rng': random.getstate()}, f)
Try something, then undo the draws
Peek at the next values without consuming them.
import random
saved = random.getstate()
preview = [random.random() for _ in range(3)]
random.setstate(saved)
Clone a generator
Copy one Random instance into another.
import random
clone = random.Random()
clone.setstate(rng.getstate())

Examples

1. Replay the same draws
import random random.seed(42) state = random.getstate() first = [random.randint(1, 9) for _ in range(5)] random.setstate(state) again = [random.randint(1, 9) for _ in range(5)] (first, again)
Returns
([2, 1, 5, 4, 4], [2, 1, 5, 4, 4])
2. What the state contains
import random random.seed(42) state = random.getstate() (state[0], len(state[1]), state[1][-1], state[2])
Returns
(3, 625, 624, None)
3. The first word after seeding
import random random.seed(42) random.getstate()[1][0]
Returns
2147483648
4. Rewind from the middle
import random random.seed(42) random.random() saved = random.getstate() x = random.random() random.setstate(saved) random.random() == x
Returns
True
5. The gauss() cache travels too
import random r = random.Random(42) r.gauss() r2 = random.Random() r2.setstate(r.getstate()) r.gauss() == r2.gauss()
Returns
True
6. A wrong-size state
import random random.setstate((3, (1, 2, 3), None))
Returns
ValueError: state vector is the wrong size
7. A wrong version
import random random.setstate((4, (), None))
Returns
ValueError: state with version 4 passed to Random.setstate() of version 3

Pitfalls

1. Re-seeding to rewind
seed() goes back to the START of the sequence. To repeat a value from the middle you need the state from just before it.
seed again
import random
random.seed(42)
random.random()
x = random.random()
random.seed(42)
random.random() == x
False
getstate / setstate
import random
random.seed(42)
random.random()
saved = random.getstate()
x = random.random()
random.setstate(saved)
random.random() == x
True
2. SystemRandom has no state
SystemRandom reads os.urandom(); there is nothing to save, so both methods raise.
SystemRandom
import random
random.SystemRandom().getstate()
NotImplementedError: System entropy source does not have state.
Random(seed)
import random
random.Random(42).getstate()[0]
3

When to use

Use it
  • Checkpointing long simulations
  • Peeking at upcoming values, or replaying a section exactly
  • Copying the state of one Random into another
Reach for something else
  • Starting a repeatable run → seed()
  • Independent streams → separate random.Random(seed) instances
  • Exchanging states between different generator classes

Notes

CPython impl
Random.getstate returns (self.VERSION, super().getstate(), self.gauss_next); the C getstate returns the 624 state words plus the position index (0 to 624) as a 625-tuple of ints. setstate checks for a tuple of exactly 625 items and an index between 0 and 624 ("invalid state" otherwise)
Platforms
The C code reads each word as an unsigned long: 32 bits on Windows, 64 on Linux. Values that do not fit 32 bits raise OverflowError on Windows but are truncated on Linux — only hand-made states are affected
Pickling
Random instances pickle via getstate(), so pickle.dumps(rng) also captures the exact position

FAQ

state = random.getstate() saves it, random.setstate(state) restores it. The state is a plain tuple, so it can be pickled with your other data.