The random.seed() method is used to generate pseudo-random numbers.
The seed is the starting point for the sequence and determines the subsequent sequence of numbers that the random number generator will produce.
This can be useful for tasks like reproducible scientific simulations or testing where you want consistent results.
Syntax
random.seed(a=None, version=2)
Parameters
- a(optional): This is the seed value. The default value is None. If a is omitted or None, the current system time is used.
- version: This specifies how the provided seed should be interpreted. The default value is 2.
Return value
It returns a random value.
Example 1: Basic Usage
import random
random.seed(0) # Setting the seed
print(random.random())
random.seed(5) # Resetting the seed
print(random.random())
Output
0.8444218515250481
0.6229016948897019
The random.random() generates a random floating-point number between 0.0 and 1.0.
If you execute this code multiple times with the seed value 0 and 5, it will generate the same sequence of random numbers each time.
Example 2 : Using the same seed value twice
import random
random.seed(10) # Setting the seed
print(random.random()) # Generates a random number
print(random.randint(1, 100)) # Generates a random integer between 1 and 100
random.seed(10) # Re-setting the same seed
print(random.random()) # Generates the same first random number as before
print(random.randint(1, 100)) # Generates the same second random number as before
Output
0.5714025946899135
55
0.5714025946899135
55
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.