The setstate()
method sets/restores the state of the pseudo-random number generator to the specified state. This method is mainly used with the getstate() method where we capture the state of the random object.
random.setstate(state)
state
: This is the generator’s internal state.import randomrandom_num = random.random()print("Random number before saving state - ", random_num)random_state = random.getstate()random_num = random.random()print("Random number after saving state - ", random_num)random.setstate(random_state)random_num = random.random()print("Random number after restoring state - ", random_num)
Line 1: We import the random
module.
Lines 3–5: We generate a random number and print it before saving the state of the random object.
Line 7: We save the state of the random object.
Lines 9–11: We generate a random number and print it after saving the state of the random object.
Line 13: We restore the state of the random object to the saved state in Line 7 using the setstate()
method.
Lines 15–17: We generate a random number and print it after restoring the state of the random object.