random
One hidden Mersenne Twister generator behind a set of module functions: random() for floats, randint() for ints, choice/sample/shuffle for sequences. Seed it and every run repeats exactly. Never use it for passwords or tokens: that is what the secrets module is for.
import random from random import randint, choice, shuffle
Demo
import random random.seed(42) [random.randint(1, 6) for _ in range(10)]
seed(42) and seed(-42) give identical rolls: an int seed is used by its absolute value. A string seed is hashed with SHA-512 into a large int, so "hello" starts a completely different sequence. In the pick tab, sample() refuses to draw 2 distinct items from a 1-item list (ValueError), while choices() happily repeats; an empty list fails already at choice() with IndexError.
Members
Common patterns
import random random.seed(2026) sample = random.sample(population, 100)
import random rng = random.Random(42) roll = rng.randint(1, 6)
import secrets token = secrets.token_urlsafe(32) pin = ''.join(secrets.choice('0123456789') for _ in range(6))
import random loot = random.choices(['common', 'rare', 'epic'], weights=[80, 15, 5], k=10)
Examples
Pitfalls
import random random.seed(42) cards = ['A', 'K', 'Q', 'J'] cards = random.shuffle(cards) print(cards)
import random random.seed(42) cards = ['A', 'K', 'Q', 'J'] random.shuffle(cards) cards
import random random.seed(2026) ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=12))
import secrets token = secrets.token_urlsafe(16) len(token)
When to use
- Simulations, games, randomized tests and sampling data
- Reproducible experiments: seed() or Random(seed) replays the exact sequence
- Shuffling, picking winners, weighted random choices
- Passwords, tokens, keys, salts, anything an attacker must not guess → secrets
- Large numeric arrays of random numbers → numpy.random (vectorized)
- Sharing one sequence between threads that must be reproducible → one Random instance per thread
Notes
FAQ
No. It is a pseudo-random generator (Mersenne Twister): every output follows deterministically from its internal state of 624 32-bit words. At import the state is seeded from os.urandom(), so unseeded runs differ, but the numbers are statistically random, not unpredictable.