Random Module
The random module generates pseudo-random numbers and makes random selections, which is useful for simulations, sampling data, shuffling datasets, and testing.
Generating Random Numbers
import random
print(random.random()) # random float between 0.0 and 1.0
print(random.randint(1, 100)) # random integer between 1 and 100 (inclusive)
print(random.uniform(1, 10)) # random float between 1 and 10
Random Selection from a Sequence
import random
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors)) # pick one random item
print(random.sample(colors, 2)) # pick 2 unique random items
random.shuffle(colors) # shuffle the list in place
print(colors)
Setting a Seed for Reproducibility
Setting a seed makes random results reproducible, which is critical in data science when you need consistent, repeatable results across multiple runs, such as when splitting data for a Machine Learning model.
random.seed(42)
print(random.randint(1, 100)) # will always produce the same value when seed is 42
Coming Up Next
Next, you'll learn the json module - essential for working with data exchanged with web APIs.
More Tools in the Module
Beyond the basics, a handful of functions cover most practical needs.
import random
random.randrange(0, 100, 5) # a multiple of 5 from 0 to 95
random.choices(["A", "B", "C"], k=5) # 5 picks WITH replacement
random.choices(["win", "lose"], weights=[1, 9], k=10) # weighted picks
random.gauss(50, 10) # normal distribution, mean 50, sd 10
random.normalvariate(50, 10) # same idea, thread-safe
The key difference to remember: sample() picks without replacement, so every item appears at most once, while choices() picks with replacement, so items can repeat. Bootstrapping, a common statistics technique, relies on sampling with replacement.
Worked Example: A Simple Simulation
Simulations answer questions that are hard to solve with formulas. Suppose a support desk wants a rough idea of how often more than 12 tickets arrive in one hour, when each of 40 customers has a small chance of raising a ticket.
import random
random.seed(7)
TRIALS = 10_000
CUSTOMERS = 40
CHANCE = 0.25
busy_hours = 0
for _ in range(TRIALS):
tickets = sum(1 for _ in range(CUSTOMERS) if random.random() < CHANCE)
if tickets > 12:
busy_hours += 1
print(f"Estimated share of busy hours: {busy_hours / TRIALS:.2%}")
Each trial plays out one hour, and the loop repeats it many times. The share of trials that exceed 12 tickets is your estimate. Because the seed is fixed, a teammate running the script gets the same answer, which makes results easy to review.
random vs NumPy vs secrets
| Need | Use |
|---|---|
| A few random values in plain Python | random |
| Millions of values or random arrays | numpy.random.default_rng(seed) |
| Passwords, tokens, OTPs or anything security-related | secrets |
The random module uses the Mersenne Twister algorithm. It is fast and statistically good, but its output can be predicted, so it must never be used to generate passwords or security tokens. The secrets module is designed for that.
For isolated experiments, create your own generator with rng = random.Random(42). It keeps its own state, so other code calling random functions cannot disturb your sequence.
Common Mistakes
- Writing
colors = random.shuffle(colors); shuffle returnsNoneand changes the list in place. - Expecting
randint(1, 10)to exclude 10; both ends are included, unlikerandrange. - Setting a seed inside a loop, which restarts the sequence and repeats the same numbers.
- Seeding Python's
randomand assuming NumPy or scikit-learn are seeded too; each has its own generator.
Random Splits Without Libraries
Sometimes you just need a quick train and test split in plain Python, for example in a coding interview. Shuffle a copy of the data with a fixed seed, then slice it.
rows = list(range(100))
rng = random.Random(42)
rng.shuffle(rows)
cut = int(len(rows) * 0.8)
train, test = rows[:cut], rows[cut:]
Shuffling a copy keeps the original order safe, and the private generator means the split is the same every time you rerun the notebook, even if other cells use random numbers in between.