random.setstate() in Python (original) (raw)

Last Updated : 17 May, 2020

**Random** module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.

random.setstate()

The setstate() method of the random module is used in conjugation with the getstate() method. After using the getstate() method to capture the state of the random number generator, the setstate() method is used to restore the state of the random number generator back to the specified state.

The setstate() method requires a state object as a parameter which can be obtained by invoking the getstate() method.

Example 1:

import random

state = random.getstate()

num = random.random()

print ( "A random number of the captured state: " + str (num))

num = random.random()

print ( "Another random number: " + str (num))

random.setstate(state)

num = random.random()

print ( "The random number of the previously captured state: " + str (num))

Output:

A random number of the captured state: 0.8059083574308233
Another random number: 0.46568313950438245
The random number of the previously captured state: 0.8059083574308233

Example 2:

import random

list1 = [ 1 , 2 , 3 , 4 , 5 ]

state = random.getstate()

print (random.sample(list1, 3 ))

random.setstate(state)

print (random.sample(list1, 3 ))

Output:

[5, 2, 4] [5, 2, 4]

Similar Reads