Python random.getstate()

Python random.getstate()

The random() module is used to generate random numbers in Python. These numbers are not actually random, but rather pseudo-random. This means that these randomly generated numbers can be determined.

random.getstate()

The getstate() method of the random module returns an object containing the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. This method is passed no arguments.

Example 1:

import random
 
 
# remember this state
state = random.getstate()
 
# print 10 random numbers
print(random.sample(range(20), k = 10))
 
# restore state
random.setstate(state)
 
# print same first 5 random numbers
# as above
print(random.sample(range(20), k = 5))

Output:

[16, 1, 0, 11, 19, 3, 7, 5, 10, 13]
[16, 1, 0, 11, 19]

Example 2:

import random
   
 
list1 = [1, 2, 3, 4, 5, 6]
     
# Get the state
state = random.getstate()
 
# prints a random value from the list
print(random.choice(list1))
   
# Set the state
random.setstate(state)
 
# prints the same random value
# from the list
print(random.choice(list1))

Output:

3
3

Leave a Reply

Your email address will not be published. Required fields are marked *