Python random.seed(): Repeatable Random Numbers
Python's random.seed() sets where the random number generator starts, so a program gets the same "random" numbers every run.
Read Random Numbers in Python first.
Get the same numbers every run
The random module does not make truly random numbers. It works them out from a starting value called the seed. Give it a fixed seed and the picks repeat.
import random
random.seed(7)
print(random.randint(1, 100))
print(random.randint(1, 100))
Press Run a few times. It prints 42, then 20, every time.
Set the seed again to replay
Calling seed() again with the same value restarts the same sequence.
import random
random.seed(7)
first = random.randint(1, 100)
random.seed(7)
again = random.randint(1, 100)
print(first, again)
This prints 42 42. Without the second seed(7), again would be the next number in the sequence, 20.
One extra call changes every pick after it
A seed repeats the numbers only for the same calls in the same order. One extra randint() shifts the whole sequence.
import random
random.seed(7)
random.randint(1, 100) # an extra pick nobody prints
print(random.randint(1, 100))
This prints 20, not 42. The extra call used up 42. If a seeded test suddenly gives new numbers, look for an added or removed call.
When to use a seed
Use a fixed seed when you need to repeat a run: testing a game, finding a bug that happens only sometimes, or sharing a result. Leave it out when players should get new numbers each time.
import random
random.seed()
print(random.randint(1, 6))
random.seed() with no value seeds from the system, like a fresh program does. This output changes every run.
Note: A seed makes numbers predictable, so never use random for passwords — use the secrets module. This lesson leaves it out.
See also: Random choices from a list.
Your turn
Import random and set the seed to 5. Then roll three dice with random.randint(1, 6) and print each roll.
# import the module, set the seed, then print three rolls of randint(1, 6)
Expected output
5
3
6