random.getstate() in Python

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.getstate()

The getstate() method of the random module returns an object with the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. There are no parameters passed in this method.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

import random
  
  
# remeber 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)) 

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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)) 

chevron_right


Output:

3
3
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.