Python Random seed() Method

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.

Usage of Python Random seed() Method

Syntax

random.seed(a=None, version=2)

Parameters

  1. a(optional): This is the seed value. The default value is None. If a is omitted or None, the current system time is used.
  2. 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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.