Skip to main content Brad's PyNotes

Random Module: Random Number Generation and Sampling

TL;DR

The random module provides functions for generating random numbers, sampling from sequences, shuffling data, and seeding for reproducible randomness in simulations and games.

Interesting!

Python’s random module uses the Mersenne Twister algorithm, which has a period of 2^19937-1 - that’s a number with about 6000 digits, making it extremely unlikely to repeat patterns in practical applications.

Basic Random Operations

python code snippet start

import random

# Random floats between 0 and 1
print(random.random())          # 0.8444218515250481

# Random integers
print(random.randint(1, 10))    # Random int from 1 to 10 (inclusive)
print(random.randrange(0, 100, 5))  # Random multiple of 5 from 0 to 95

# Random choice from sequence
colors = ['red', 'green', 'blue', 'yellow']
print(random.choice(colors))    # Random color

# Multiple random choices (with replacement)
print(random.choices(colors, k=3))  # ['red', 'blue', 'red']

# Sample without replacement
print(random.sample(colors, 2))     # ['green', 'yellow']

python code snippet end

Shuffling and Sampling

python code snippet start

# Shuffle a list in-place
deck = list(range(1, 53))  # Standard deck of cards
random.shuffle(deck)
print(deck[:5])  # First 5 cards

# Weighted random choices
items = ['apple', 'banana', 'cherry']
weights = [1, 2, 3]  # Cherry is 3x more likely than apple
selections = random.choices(items, weights=weights, k=10)
print(selections)

# Random sampling for statistics
population = list(range(1000))
sample = random.sample(population, 50)  # 50 random items
print(f"Sample mean: {sum(sample) / len(sample)}")

python code snippet end

Probability Distributions

python code snippet start

import random

# Uniform distribution
print(random.uniform(1.5, 3.5))    # Random float between 1.5 and 3.5

# Normal (Gaussian) distribution
print(random.gauss(0, 1))          # Mean=0, standard deviation=1
print(random.normalvariate(100, 15))  # Mean=100, std dev=15

# Exponential distribution
print(random.expovariate(1/5))     # Lambda = 1/5 (mean = 5)

# Triangular distribution
print(random.triangular(0, 100, 20))  # Min=0, max=100, mode=20

python code snippet end

Reproducible Randomness with Seeds

python code snippet start

# Set seed for reproducible results
random.seed(42)
print(random.random())  # Always prints 0.6394267984578837

# Same seed, same sequence
random.seed(42)
sequence1 = [random.random() for _ in range(5)]

random.seed(42)
sequence2 = [random.random() for _ in range(5)]

print(sequence1 == sequence2)  # True - identical sequences

# Save and restore random state
state = random.getstate()
random.random()  # Change the state
random.setstate(state)  # Restore previous state

python code snippet end

Practical Applications

Password Generator

python code snippet start

import string

def generate_password(length=12):
    characters = (string.ascii_letters + 
                 string.digits + 
                 "!@#$%^&*")
    return ''.join(random.choices(characters, k=length))

print(generate_password())      # Ky8#mP2$nX9@
print(generate_password(16))    # aB4$dE7&iJ0!mN3%

python code snippet end

Data Simulation

python code snippet start

def simulate_dice_rolls(num_rolls=1000):
    """Simulate rolling two dice"""
    results = []
    for _ in range(num_rolls):
        die1 = random.randint(1, 6)
        die2 = random.randint(1, 6)
        results.append(die1 + die2)
    
    # Count occurrences
    counts = {i: results.count(i) for i in range(2, 13)}
    return counts

results = simulate_dice_rolls(10000)
for sum_val, count in results.items():
    probability = count / 10000
    print(f"Sum {sum_val}: {probability:.3f}")

python code snippet end

Random Testing Data

python code snippet start

def generate_test_users(count=100):
    """Generate random test user data"""
    first_names = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
    last_names = ['Smith', 'Johnson', 'Brown', 'Davis', 'Wilson']
    
    users = []
    for i in range(count):
        user = {
            'id': i + 1,
            'first_name': random.choice(first_names),
            'last_name': random.choice(last_names),
            'age': random.randint(18, 80),
            'score': random.normalvariate(75, 10),  # Normal distribution
            'active': random.random() > 0.1  # 90% chance of being active
        }
        users.append(user)
    
    return users

test_users = generate_test_users(5)
for user in test_users:
    print(f"{user['first_name']} {user['last_name']}: {user['age']} years, score: {user['score']:.1f}")

python code snippet end

Security Considerations

python code snippet start

# For cryptographic purposes, use secrets module instead
import secrets

# Cryptographically secure random
secure_token = secrets.token_hex(16)    # 32-char hex string
secure_int = secrets.randbelow(100)     # Secure random int 0-99
secure_choice = secrets.choice(['A', 'B', 'C'])  # Secure choice

print(f"Secure token: {secure_token}")

# Use random module for simulations, games, testing
# Use secrets module for passwords, tokens, cryptographic keys

python code snippet end

The random module is essential for simulations, testing, games, and any application requiring probabilistic behavior or random sampling.

Random operations often pair well with string constants for password generation and itertools for sequence generation in data simulation tasks.

Reference: Python Random Module Documentation