The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create a local generator | rng = random.Random(seed) | View examples |
| Capture generator state | state = rng.getstate() | View examples |
| Restore generator state | rng.setstate(state) | View examples |
| Draw from range semantics | value = rng.randrange(start, stop, step) | View examples |
| Choose one element | item = rng.choice(population) | View examples |
| Sample without replacement | items = rng.sample(population, k=3) | View examples |
| Sample by relative weight | draws = rng.choices(population, weights=weights, k=100) | View examples |
| Draw a uniform float | value = rng.uniform(low, high) | View examples |
| Draw from a normal model | value = rng.normalvariate(mu, sigma) | View examples |
| Generate random bytes | token = secrets.token_bytes(32) | View examples |
| Generate a URL-safe token | token = secrets.token_urlsafe(32) | View examples |
| Choose securely | character = secrets.choice(alphabet) | View examples |
| Compute an arithmetic mean | center = statistics.mean(values) | View examples |
| Compute a median | center = statistics.median(values) | View examples |
| Find all most-common values | modes = statistics.multimode(values) | View examples |
| Estimate sample spread | spread = statistics.stdev(sample) | View examples |
| Measure population spread | spread = statistics.pstdev(population) | View examples |
| Compute linear correlation | coefficient = statistics.correlation(xs, ys) | View examples |
| Estimate sample quartiles | cuts = statistics.quantiles(values, n=4, method='exclusive') | View examples |
| Summarize observed endpoints | cuts = statistics.quantiles(values, n=4, method='inclusive') | View examples |
The random module provides deterministic pseudo-random generators for simulation, while secrets uses operating-system entropy for credentials and security tokens. The statistics module supplies transparent descriptive tools, but correct results still depend on sampling design, missing-data policy, numeric types, and the meaning of the population being summarized.
Step by step
Detailed examples
Own generator state for reproducible simulations
Create a dedicated random.Random instance instead of mutating the module-global generator in libraries. A seed recreates a pseudo-random state for debugging but is not secret entropy. Record the algorithm/runtime context when long-term replay matters; getstate and setstate can checkpoint a run but their serialized representation is Python-specific.
import random
rng = random.Random(23)
state = rng.getstate()
first = [rng.randrange(10) for _ in range(4)]
rng.setstate(state)
second = [rng.randrange(10) for _ in range(4)]
print(first)
print(first == second) [4, 1, 0, 9]
TrueSelect discrete outcomes without off-by-one errors
randrange follows range semantics and excludes stop; randint(a, b) includes both endpoints. choice selects one element, choices samples with replacement, and sample selects unique positions without replacement. Sampling a population containing repeated values treats each position as a possible selection unless counts is used to express multiplicities.
import random
rng = random.Random(7)
sample = rng.sample(["a", "b", "c", "d", "e"], k=3)
print(sample)
print(len(set(sample)) == 3) ['c', 'b', 'd']
TrueModel weights and distributions explicitly
choices accepts relative weights or cumulative weights and samples with replacement. Distribution functions such as uniform, gauss, normalvariate, expovariate, and triangular encode specific mathematical models; validate parameter units and domain assumptions. Floating-point endpoints and tails need policy-driven bounds rather than equality tests.
import random
rng = random.Random(1)
draws = rng.choices(["disabled", "enabled"], weights=[0, 5], k=4)
print(draws) ['enabled', 'enabled', 'enabled', 'enabled']Use secrets for security-sensitive choices
random is predictable from state and must not generate passwords, reset links, session identifiers, salts, or cryptographic nonces. secrets delegates to the operating system's strongest available source. Token output is intentionally nondeterministic; validate entropy requirements in bytes or bits rather than assuming a displayed character count provides equivalent entropy.
import secrets
token = secrets.token_bytes(16)
print(type(token).__name__)
print(len(token))
print(len(token) * 8) bytes
16
128Choose a center that matches the data
mean uses every value and is sensitive to outliers; median is robust to extremes; mode and multimode describe frequency. fmean converts input to float and is usually faster, while mean preserves supported numeric types where possible. Empty data and mixed incompatible numeric types need explicit handling rather than fallback zeroes.
import statistics
values = [2, 3, 3, 4, 100]
print(statistics.mean(values))
print(statistics.median(values))
print(statistics.multimode(values)) 22.4
3
[3]Distinguish samples from populations
pstdev and pvariance divide by population size; stdev and variance apply Bessel's correction for sample estimates and require at least two observations. covariance and correlation describe paired observations and do not establish causation. NaN values can break ordering-based functions, so filter or reject them according to a documented missing-data policy.
import statistics
values = [1, 2, 3]
print(statistics.pvariance(values))
print(statistics.variance(values))
print(statistics.correlation(values, [2, 4, 6])) 0.6666666666666666
1
1.0Report distributions with explicit conventions
quantiles divides data into equal-probability intervals using exclusive or inclusive conventions. Exclusive is suited to samples from a larger population; inclusive treats the observed minimum and maximum as population endpoints. Statistics do not repair selection bias, dependent observations, censoring, or a changing process; preserve raw counts and definitions beside summaries.
import statistics
values = [10, 20, 30, 40, 50]
print(statistics.quantiles(values, n=4, method="inclusive"))
print(min(values), max(values)) [20.0, 30.0, 40.0]
10 50Local code tester
Summarize a reproducible sample
Draw a local deterministic sample and report its center and spread without changing global generator state.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Python Software Foundationrandom — Generate pseudo-random numbersdocs.python.org
- Python Software Foundationsecrets — Generate secure random numbersdocs.python.org
- Python Software Foundationstatistics — Mathematical statistics functionsdocs.python.org
- Python Software FoundationFloating-Point Arithmetic: Issues and Limitationsdocs.python.org
- Python Software Foundationhashlib — Secure hashes and message digestsdocs.python.org
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



