Use Local Seeded Random Generators
Core idea
random.Random(seed) creates a separate pseudorandom generator. With the same seed and same sequence of calls, two generators in the same environment reproduce results. randrange(stop) excludes stop, choice selects one element, and sample selects positions without replacement.
from random import Randoma, b = Random(42), Random(42)print([a.randrange(10) for _ in range(4)] == [b.randrange(10) for _ in range(4)])Separate generators seeded identically give matching results for matching calls.
Check a bounded draw
from random import Randomrng = Random(7)print(all(0 <= rng.randrange(6) < 6 for _ in range(20)))Every draw is between zero and five inclusive.
Sample unique labels
from random import Randomlabels = ["A", "B", "C", "D"]selected = Random(3).sample(labels, 2)print(len(selected), len(set(selected)))With unique input labels, sampling two positions without replacement gives two distinct values.
Common mistake
Do not reseed before each draw. Reproducibility of higher-level algorithms across Python versions is not guaranteed. random is unsuitable for credentials or security tokens.
Practice
Create two local generators with the same seed, run five identical draws, then vary the seed and compare sequences without assuming they must differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Seeded random generators
Check your understanding of random generators.
What is printed?
from random import Randoma,b=Random(8),Random(8)print(a.random()==b.random())What is printed?
from random import Randomrng = Random(3)print(all(0 <= rng.randrange(4) < 4 for _ in range(3)))What is printed?
from random import Randomprint(len(set(Random(2).sample([1,2,3,4],3))))Which task should not use random.Random?