
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python random.setstate() Function
The random.setstate() function in Python is used to restores the internal state of the generator to what it was at the time getstate() was called. The state parameter should have been obtained from a previous call to getstate(). This function is part of the random module, which provides various functions to generate random numbers and sequences.
The primary purpose of this function is to restore the internal state of the random number generator to a previously captured state.
Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using random static object.
Syntax
Following is the syntax of the random.setstate() function −
random.setstate(state)
Parameters
The Python random.setstate() function accepts a single parameter −
state − An object capturing the current internal state of the generator, obtained from a previous call to getstate().
Return Value
The random.setstate() function does not return any value.
Example 1
Let us look at an example using python random.setstate() function.
In the following code, a list of length 15 is defined, then random.setstate() captures the current state of the random number generator. Then, the code generates a list of size 10 with the current random state. Thereafter, the state is restored using random.setstate(), this ensures following output list of size 5 follows the same randomness as before.
import random list=[11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] state = random.getstate() print(random.sample(list, k = 10)) random.setstate(state) print(random.sample(list, k = 5))
Following is the output of the code −
[23, 21, 18, 11, 25, 16, 19, 22, 24, 13] [23, 21, 18, 11, 25]
Example 2
In this example we will use the random.setstate() function to restore the state of the random number generator to a previously captured state.
import random # Initialize the random number generator random.seed(42) # Generate a sample of 10 numbers from a range of 20 print(random.sample(range(30), k=10)) # Capture the current state state = random.getstate() # Generate a sample of 20 numbers from a range of 20 print(random.sample(range(20), k=20)) # Restore the state using the setstate() function random.setstate(state) # Generate another sample of 10 numbers from the same range print(random.sample(range(20), k=10))
When we run the above program, it produces the following result −
[20, 3, 0, 23, 8, 7, 24, 4, 28, 17] [2, 18, 13, 1, 0, 16, 3, 17, 8, 9, 15, 11, 12, 5, 6, 4, 7, 10, 14, 19] [2, 18, 13, 1, 0, 16, 3, 17, 8, 9]
Example 3
In this example, we'll demonstrate how to use the random.setstate() function to reproduce the same random number by capturing and restoring the state of the random number generator.
import random # Initialize the random number generator and get state random.seed(0) initial_state = random.getstate() # Generate and print random number print(random.random()) print(random.random()) # Setting the seed back to 0 resets the RNG back to the original state random.seed(0) new_state = random.getstate() assert new_state == initial_state # Since the state of the generator is the same as before, it will produce the same sequence print(random.random()) # We could also achieve the same outcome by resetting the state explicitly random.setstate(initial_state) print(random.random())
The output of the above code is as follows −
0.8444218515250481 0.7579544029403025 0.8444218515250481 0.8444218515250481
Example 4
Here is another example that compare the time taken to generate random numbers using random.seed(), the random.setstate() and random.setstate() functions.
import random import timeit # Measure the time taken to generate random numbers using seed() t1 = timeit.timeit(stmt="""random.seed(42) random.randint(1, 10)""", number=10000, setup="import random") # Measure the time taken to generate random numbers using setstate() and setstate() t2 = timeit.timeit(stmt="""random.randint(1, 10) random.setstate(state)""", number=10000, setup="""import random state = random.getstate()""") print("Time taken using seed():", t1) print("Time taken using setstate() and setstate():", t2)
Following is an output of the above code −
Time taken using seed(): 0.12103769998066127 Time taken using setstate() and setstate(): 0.06645569996908307