Sample data and make experiments repeatable
Use random and statistics with a predictable test input.
Jump to the automation labThe random module can pick one item with choice(), shuffle a list in place with shuffle(), or draw distinct positions with sample(). randint(a, b) includes both endpoints.
Pass a random.Random(seed) instance into a helper when you need repeatable experiments and tests. This keeps the rest of the program’s random state separate. Use statistics.mean() or statistics.median() to summarize the sampled values.
Four values are available for the draw.
Worked examples
Compare picking, rolling, and shuffling
The original list changes when shuffle runs. The same seed lets you replay this sequence.
from random import Random
rng = Random(7)
colors = ["amber", "blue", "green"]
print(rng.choice(colors))
print(rng.randint(1, 6))
rng.shuffle(colors)
print(colors)Run the example and practice
Change sample_summary to return both the median and the range (largest minus smallest). Keep sampling through rng. Print the two results on separate lines.
Target output
25.0
30Show a hint
Import median and return a pair. Unpack that pair into two names before printing.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
from random import Random
from statistics import median
def sample_summary(values, size, rng):
picked = rng.sample(values, size)
return median(picked), max(picked) - min(picked)
middle, spread = sample_summary([10, 20, 30, 40], 4, Random(7))
print(f"{middle:.1f}")
print(spread)Automation lab
Sample rows for an audit
Pick three turnaround times from a spreadsheet export. Keep the seed so someone else can reproduce the sample.
Ready
Run the example to see the output here.
Increase the sample size to 5, then run twice to check that the sample repeats.
Further reading in Automate the Boring Stuff with Python by Al Sweigart