On this page
random
Prev: quopri | Up: stdlib_module | Next: re
Rel: numbers, math, cmath, decimal, fractions
Ref: docs.python.org — random
Tags: #public #python3 #stdlib
Import
import random
Overview
Fast Mersenne Twister pseudo-random number generator for simulations, games, sampling, shuffling, and randomized tests (randint, randrange, choice, choices, sample, shuffle, uniform, gauss). Never use random for security, passwords, or tokens—use secrets for cryptographic randomness.
Quick Start
import random
rng = random.Random(42) # isolated, reproducible generator
assert rng.randint(1, 6) == 6
assert rng.choice(["rock", "paper", "scissors"]) in {"rock", "paper", "scissors"}
assert len(rng.sample(range(100), k=5)) == 5
Implementation Walkthrough
1. Reproducible Isolated Generators (random.Random(seed))
In libraries and tests, instantiate random.Random(seed) instead of calling random.seed(...) globally so unrelated modules never interfere with your sequence:
import random
def deal_hand(seed: int) -> list[int]:
rng = random.Random(seed)
deck = list(range(52))
rng.shuffle(deck)
return deck[:5]
assert deal_hand(7) == deal_hand(7)
2. Weighted Sampling With Replacement (choices) vs. Without Replacement (sample)
import random
rng = random.Random(0)
# With replacement and weights:
draws = rng.choices(["common", "rare", "epic"], weights=[80, 18, 2], k=10)
# Without replacement (unique picks):
winners = rng.sample(["Ada", "Lin", "Grace", "Alan"], k=2)
assert len(draws) == 10 and len(set(winners)) == 2
Gotchas & Boundaries
- Not cryptographically secure: Never use
randomfor auth tokens, session IDs, salts, or password resets; use secrets. randint(a, b)is inclusive on BOTH ends ([a, b]), whereasrandrange(a, b)is half-open ([a, b)) likerange().shuffle()mutates the list in place and returnsNone: Copy first (list(seq)) or usesample(seq, len(seq))if you want a new shuffled list.- Avoid global
random.seed()in library code: Pass an explicitrandom.Randominstance instead.
Common Functions
- random.betavariate() —
betavariate(alpha, beta)— Beta distribution. - random.binomialvariate() —
binomialvariate(n=1, p=0.5)— Binomial random variable. - random.choice() —
choice(seq)— Choose a random element from a non-empty sequence. - random.choices() —
choices(population, weights=None, *, cum_weights=None, k=1)— Return a k sized list of population elements chosen with replacement. - random.expovariate() —
expovariate(lambd=1.0)— Exponential distribution. - random.gammavariate() —
gammavariate(alpha, beta)— Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. - random.gauss() —
gauss(mu=0.0, sigma=1.0)— Gaussian distribution. - random.getrandbits() —
getrandbits(k, /)— getrandbits(k) -> x. Generates an int with k random bits. - random.getstate() —
getstate()— Return internal state; can be passed to setstate() later. - random.lognormvariate() —
lognormvariate(mu, sigma)— Log normal distribution. - random.normalvariate() —
normalvariate(mu=0.0, sigma=1.0)— Normal distribution. - random.paretovariate() —
paretovariate(alpha)— Pareto distribution. alpha is the shape parameter. - random.randbytes() —
randbytes(n)— Generate n random bytes. - random.randint() —
randint(a, b)— Return random integer in range [a, b], including both end points. - random.random() —
random()— random() -> x in the interval [0, 1). - random.randrange() —
randrange(start, stop=None, step=1)— Choose a random item from range(stop) or range(start, stop[, step]). - random.sample() —
sample(population, k, *, counts=None)— Chooses k unique random elements from a population sequence. - random.seed() —
seed(a=None, version=2)— Initialize internal state from a seed. - random.setstate() —
setstate(state)— Restore internal state from object returned by getstate(). - random.shuffle() —
shuffle(x)— Shuffle list x in place, and return None. - random.triangular() —
triangular(low=0.0, high=1.0, mode=None)— Triangular distribution. - random.uniform() —
uniform(a, b)— Get a random number in the range [a, b) or [a, b] depending on rounding. - random.vonmisesvariate() —
vonmisesvariate(mu, kappa)— Circular data distribution. - random.weibullvariate() —
weibullvariate(alpha, beta)— Weibull distribution.
Classes & Objects
- random.Random — Random number generator base class used by bound module functions. (Methods:
.betavariate(),.binomialvariate(),.choice(),.choices(),.expovariate(),.gammavariate()) - random.SystemRandom — Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). (Methods:
.betavariate(),.binomialvariate(),.choice(),.choices(),.expovariate(),.gammavariate())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/cmath
- tuts/python3/stdlib_module/decimal
- tuts/python3/stdlib_module/fractions
- tuts/python3/stdlib_module/math
- tuts/python3/stdlib_module/numbers
- tuts/python3/stdlib_module/quopri
- tuts/python3/stdlib_module/re
- tuts/python3/stdlib_module/secrets
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/popular_application_domains/data_science_and_machine_learning
Related notes
- tuts/python3/stdlib_module/cmath Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/decimal Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/fractions Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/math Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/numbers Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/quopri Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib