What is the random.setstate() method in python?

Overview

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.

Syntax

random.setstate(state)

Parameter

  • state: This is the generator’s internal state.

Example

import random
random_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)

Explanation

  • 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.

Free Resources