Python random Module Patterns — Core Concepts

What Does the random Module Do?

Python’s random module provides pseudo-random number generation based on the Mersenne Twister algorithm. It’s part of the standard library and covers most randomness needs: picking numbers, sampling from sequences, shuffling, and generating values from statistical distributions.

Essential Functions

Random Numbers

import random

random.random()           # Float in [0.0, 1.0)
random.uniform(1.5, 9.5)  # Float in [1.5, 9.5]
random.randint(1, 10)      # Integer in [1, 10] (inclusive)
random.randrange(0, 100, 5)  # Integer from 0,5,10,...,95

Working with Sequences

colors = ["red", "blue", "green", "yellow"]

random.choice(colors)         # Pick one random element
random.choices(colors, k=3)   # Pick 3 with replacement (can repeat)
random.sample(colors, k=2)    # Pick 2 without replacement (no repeats)
random.shuffle(colors)        # Shuffle in place (modifies the list)

Weighted Choices (Python 3.6+)

items = ["common", "rare", "legendary"]
weights = [70, 25, 5]  # Probability proportions

random.choices(items, weights=weights, k=10)
# Mostly "common", occasionally "rare", rarely "legendary"

You can also use cum_weights for cumulative weights, which is faster when calling choices many times with the same weights.

Seeding: Reproducible Randomness

The random module generates numbers from a deterministic formula. Setting the seed ensures you get the same sequence every time:

random.seed(42)
print(random.random())  # Always 0.6394267984578837

random.seed(42)
print(random.random())  # Same number again

When to seed:

  • Testing — reproducible test data
  • Debugging — reproduce a specific run
  • Scientific experiments — repeatable simulations

When NOT to seed: Production code where you want different results each run. Python auto-seeds from the OS entropy source on startup.

Distributions

The module provides functions for common statistical distributions:

random.gauss(mu=0, sigma=1)         # Gaussian (normal) distribution
random.expovariate(lambd=1.5)       # Exponential distribution
random.betavariate(alpha=2, beta=5)  # Beta distribution
random.triangular(low=0, high=10, mode=3)  # Triangular distribution
random.lognormvariate(mu=0, sigma=1)  # Log-normal distribution

These are useful for simulations: modeling arrival times (exponential), test scores (normal), or task durations (triangular).

Common Misconception

“random.random() is random enough for passwords.” It’s not. The Mersenne Twister is predictable — given 624 consecutive outputs, an attacker can reconstruct the internal state and predict all future values. For anything security-related, use the secrets module instead:

import secrets
secrets.token_hex(16)        # Secure random hex string
secrets.choice(["a", "b"])   # Cryptographically secure choice

Common Patterns

Random sampling for A/B tests:

def assign_group(user_id, ratio=0.5):
    rng = random.Random(user_id)  # Deterministic per user
    return "treatment" if rng.random() < ratio else "control"

Generating test data:

def fake_user():
    return {
        "age": random.randint(18, 80),
        "score": round(random.gauss(75, 15), 1),
        "tier": random.choices(["free", "pro", "enterprise"], weights=[60, 30, 10])[0],
    }

Retry with jitter:

def retry_delay(attempt, base=1.0, max_delay=30.0):
    delay = min(base * 2 ** attempt, max_delay)
    return delay * random.uniform(0.5, 1.0)  # Add jitter

When to Use What

NeedUse
Games, simulationsrandom module
Reproducible experimentsrandom with seed
Security (tokens, passwords)secrets module
NumPy array operationsnumpy.random
Parallel-safe randomnessrandom.Random() instances

One Thing to Remember

The random module is your go-to for everyday randomness — games, simulations, and test data — but always switch to secrets when security matters.

pythonrandomstdlibsimulationtesting

See Also

  • Python Scipy Scientific Computing Learn why scientists and engineers reach for SciPy when they need Python to crunch serious math problems.
  • Python Statistics Module Find out how Python's built-in statistics module helps you understand numbers — no extra installs needed.
  • Python Sympy Symbolic Math See how Python can solve algebra homework for you — with letters instead of just numbers.
  • Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
  • Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.