Random With Seed Replays The Same Draws
random.Random(seed) produces the same draws, shuffles, and samples on every replay, so tests and demos stay reproducible; unseeded instances differ.
Code
import random
# 固定种子:同一版本 Python 里序列逐次一致,测试与演示可复现
rng = random.Random(42)
print('first draw :', rng.randrange(1000))
print('next draw :', rng.randrange(1000))
# shuffle 与 sample 走同一个流:种子相同则洗牌相同
rng = random.Random(42)
deck = list(range(5))
rng.shuffle(deck)
print('shuffled :', deck)
print('sample :', rng.sample(deck, 3))
# 重放:同种子重建实例,整段序列完全一致
rng2 = random.Random(42)
print('replay :', [rng2.randrange(1000) for _ in range(2)])
# 不同种子分岔;Random() 不带种子每次都不同
print('other seed :', random.Random(7).randrange(1000))Output
Captured from a sandboxed run of this snippet in the build pipeline.
first draw : 654
next draw : 114
shuffled : [3, 1, 2, 4, 0]
sample : [1, 0, 3]
replay : [654, 114]
other seed : 331How the snippet works
Top-level bindings rng, deck, rng2 hold the demo state — nothing sits inside a function scope.
Using it
The demo output is labeled (first draw :, other seed :); each label names the call that printed it.
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `random`. Its state lives in module-level bindings: `rng`, `deck`, `rng2`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.