The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a local generatorrng = random.Random(seed)View examples
Capture generator statestate = rng.getstate()View examples
Restore generator staterng.setstate(state)View examples
Draw from range semanticsvalue = rng.randrange(start, stop, step)View examples
Choose one elementitem = rng.choice(population)View examples
Sample without replacementitems = rng.sample(population, k=3)View examples
Sample by relative weightdraws = rng.choices(population, weights=weights, k=100)View examples
Draw a uniform floatvalue = rng.uniform(low, high)View examples
Draw from a normal modelvalue = rng.normalvariate(mu, sigma)View examples
Generate random bytestoken = secrets.token_bytes(32)View examples
Generate a URL-safe tokentoken = secrets.token_urlsafe(32)View examples
Choose securelycharacter = secrets.choice(alphabet)View examples
Compute an arithmetic meancenter = statistics.mean(values)View examples
Compute a mediancenter = statistics.median(values)View examples
Find all most-common valuesmodes = statistics.multimode(values)View examples
Estimate sample spreadspread = statistics.stdev(sample)View examples
Measure population spreadspread = statistics.pstdev(population)View examples
Compute linear correlationcoefficient = statistics.correlation(xs, ys)View examples
Estimate sample quartilescuts = statistics.quantiles(values, n=4, method='exclusive')View examples
Summarize observed endpointscuts = 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

01

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.

Replay a local generator state
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)
Output
[4, 1, 0, 9]
True
Back to quick reference ↑
02

Select 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.

Sample without replacement reproducibly
import random

rng = random.Random(7)
sample = rng.sample(["a", "b", "c", "d", "e"], k=3)
print(sample)
print(len(set(sample)) == 3)
Output
['c', 'b', 'd']
True
Back to quick reference ↑
03

Model 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.

Use zero weights to make a deterministic choice
import random

rng = random.Random(1)
draws = rng.choices(["disabled", "enabled"], weights=[0, 5], k=4)
print(draws)
Output
['enabled', 'enabled', 'enabled', 'enabled']
Back to quick reference ↑
04

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.

Validate a secure token without fixing its value
import secrets

token = secrets.token_bytes(16)
print(type(token).__name__)
print(len(token))
print(len(token) * 8)
Output
bytes
16
128
Back to quick reference ↑
05

Choose 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.

Compare mean and median under an outlier
import statistics

values = [2, 3, 3, 4, 100]
print(statistics.mean(values))
print(statistics.median(values))
print(statistics.multimode(values))
Output
22.4
3
[3]
Back to quick reference ↑
06

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.

Compare sample and population variance
import statistics

values = [1, 2, 3]
print(statistics.pvariance(values))
print(statistics.variance(values))
print(statistics.correlation(values, [2, 4, 6]))
Output
0.6666666666666666
1
1.0
Back to quick reference ↑
07

Report 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.

Compute inclusive quartiles
import statistics

values = [10, 20, 30, 40, 50]
print(statistics.quantiles(values, n=4, method="inclusive"))
print(min(values), max(values))
Output
[20.0, 30.0, 40.0]
10 50
Back to quick reference ↑

Local code tester

Summarize a reproducible sample

Draw a local deterministic sample and report its center and spread without changing global generator state.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software Foundationrandom — Generate pseudo-random numbersdocs.python.org
  2. Python Software Foundationsecrets — Generate secure random numbersdocs.python.org
  3. Python Software Foundationstatistics — Mathematical statistics functionsdocs.python.org
  4. Python Software FoundationFloating-Point Arithmetic: Issues and Limitationsdocs.python.org
  5. 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.

Share feedback