How to use Python random.seed() function

  • Use random.seed() to initialize the pseudo-random number generator.
  • Choose the same elements from the list randomly every time using random.seed()
  • Use a random.seed() function with other random module functions.

How to use random.seed() function

Syntax of random.seed()

random.seed(a, version)
  • a: Optional. The seed value needed to generate a random number.
    If it is an integer it is used directly, if not it has to be converted into an integer. The default value is None, and if None, the generator uses the current system time.
  • version: An integer specifying how to convert the a parameter into an integer. Default value is 2

Example to generate the same random number every time using random.seed()

import random

print ("Random number with seed 88")
random.seed(88)
print ("first Number ", random.randint(1,10))

random.seed(88)
print ("Second Number ", random.randint(1,10))

random.seed(88)
print ("Third Number ", random.randint(1,10))
import random

print("Random number with seed 88")
# first call
random.seed(88)
print("first Number", random.randint(1, 10))

# generate a different random number
print("Second Number ", random.randint(1, 10))

# will generate a same random number as first one because seed value is same
random.seed(88) # Third call
print("Third Number", random.randint(1, 10))

Use random seed and sample function together

import random

# using random.seed() and random.sample() together
fruit_list = ["Apple", "Mango", "Banana", "Apricot", "Cherries", "Grape", "Kiwi"]

random.seed(32)
sample_list = random.sample(fruit_list, 3)
print("First sample fruit list ", sample_list)

random.seed(32)
sample_list = random.sample(fruit_list, 3)
print("Second sample fruit list ", sample_list)

Use random seed and shuffle function together

import random

numbers = [10, 20, 30, 40, 50, 60]
print("Original list: ", numbers)
random.seed(42)
random.shuffle(numbers)
print("Shuffled list ", numbers)

numbers = [10, 20, 30, 40, 50, 60]
random.seed(42)
random.shuffle(numbers)
print("Reshuffled list ", numbers)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store