Lesson 7 of 18

Random Sampling

Sampling from a Population

We rarely have access to an entire population. Instead, we take a sample — a random subset — and use it to draw conclusions about the population.

import random

population = list(range(1, 101))   # integers 1 to 100
rng = random.Random(42)

sample = rng.sample(population, 10)   # without replacement
print(round(sum(sample) / len(sample), 2))   # close to 50.5 (true mean)

Why Use a Seed?

Setting a random seed makes results reproducible — running the same code gives the same "random" numbers. Use random.Random(seed) to create a seeded instance.

Sampling With vs Without Replacement

  • Without replacement (random.sample): each element can only be chosen once. Used for surveys.
  • With replacement (random.choices): elements can be chosen multiple times. Used for bootstrapping.

Law of Large Numbers

As sample size nn increases, the sample mean xˉ\bar{x} converges to the true population mean μ\mu:

xˉ=1ni=1nxinμ\bar{x} = \frac{1}{n}\sum_{i=1}^n x_i \xrightarrow{n \to \infty} \mu

# Larger samples are more accurate
for n in [5, 20, 100]:
    s = rng.sample(population, n)
    print(f"n={n}: mean={round(sum(s)/len(s), 1)}")

Your Task

Implement sample_mean(population, n, seed) that takes a random sample of size nn (without replacement) using the given seed and returns the sample mean rounded to 2 decimal places.

Pyodide loading...
Loading...
Click "Run" to execute your code.