random.seed
Same seed in, same numbers out, on every platform. An int seed is used by its absolute value, a str or bytes seed is hashed with SHA-512 into an int, and no seed at all means fresh entropy from the operating system.
Demo
import random random.seed(42) a = [random.randint(1, 100) for _ in range(3)] random.seed(42) b = [random.randint(1, 100) for _ in range(3)] (a, b, a == b)
seed(42) and seed(-42) produce the same 0.6394267984578837: the C code takes abs() of an int before splitting it into 32-bit words for the Mersenne Twister. A string goes through SHA-512 first, so "hello" and "Hello" land on unrelated states. A float is seeded by its hash(): 1.5 is not 1 or 2, but seed(42.0) equals seed(42) because hash(42.0) == 42.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| a | None | int | float | str | bytes | bytearray | no (None) | None: seed from os.urandom() (or the time if unavailable). int: its absolute value, all bits used. str/bytes/bytearray: the bytes plus their SHA-512 digest, read as one int. float: its hash(). Anything else raises TypeError (3.11+). |
| version | int | no (2) | Only affects str and bytes seeds: 1 reproduces the narrower seeding of Python 2 / before 3.2. |
Return value
None — Nothing; the generator state is replaced and the cached gauss() value is cleared.
Common patterns
import random import sys random.seed(int(sys.argv[1]) if len(sys.argv) > 1 else None)
import random def make_users(n, seed=0): rng = random.Random(seed) return [rng.randint(18, 90) for _ in range(n)]
import random import secrets run_seed = secrets.randbits(32) print(f'seed = {run_seed}') random.seed(run_seed)
Examples
Pitfalls
import random rolls = [] for _ in range(3): random.seed(42) rolls.append(random.randint(1, 6)) rolls
import random random.seed(42) rolls = [] for _ in range(3): rolls.append(random.randint(1, 6)) rolls
import random seed_text = '42' random.seed(seed_text) [random.randint(1, 100) for _ in range(3)]
import random seed_text = '42' random.seed(int(seed_text)) [random.randint(1, 100) for _ in range(3)]
When to use
- Reproducible simulations, tests and bug reports
- Demos and tutorials whose output must match the text
- Re-randomizing from the OS: random.seed() with no argument
- Making anything secret: a known seed means known output → secrets
- Library code: seeding the shared global generator changes it for every other module → use random.Random(seed)
- Reproducing NumPy results: numpy.random has its own, separate generators
Notes
FAQ
It resets the generator's internal state from the value you give. After random.seed(42) the sequence of random(), randint(), choice() and so on is always the same, so a run can be reproduced exactly.