Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

44 matches
Lists & loops easy

Generate Data Helper for Beginners in Python

Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.

random loops lists
Python
from random import randint

def build_dataset(size: int, max_val: int) -> list[int]:
    data = []
    for _ in range(size):
        data.append(randint(1, max_val))
    return data

def summarize(data: list[int]) -> dict[str, float]:
    total = 0
    maximum = data[0]
    minimum = data[0]
    for value in data:
   …
12 0 Open
Lists & loops easy

How to Shuffle a List in Python

Shuffle a Python list in place or return a new shuffled copy using the random module.

random shuffle lists
Python
import random

def shuffle_list(items):
    shuffled = items[:]
    random.shuffle(shuffled)
    return shuffled

if __name__ == "__main__":
    original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = shuffle_list(original)
    print(f"Original: {original}")
    print(f"Shuffled: {result}")
14 0 Open
Algorithms & data structures easy

How to Sample Random Items Without Replacement in Python

Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.

random sampling algorithms
Python
import random

def sample_without_replacement(population, k):
    """Return k random items from population without replacement."""
    if k > len(population):
        raise ValueError("k cannot exceed population size")
    # Use random.sample for O(k) time, no mutation of the original
    return random.sample(populati…
15 0 Open
Comprehensions & generators easy

How to Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 0 Open
AI & LLM integration patterns easy

How to Batch Embed a List of Strings in Python

Batch embed a list of strings into deterministic pseudo-random vectors using a mock encoder class.

embedding batch-processing mock-encoder
Python
class MockEncoder:
    def __init__(self, dim=8, seed=42):
        self.dim = dim
        self.seed = seed

    def embed(self, text):
        # Deterministic pseudo-random embedding based on text content
        hash_val = hash(text)
        import random
        rng = random.Random(hash_val + self.seed)
        retu…
12 0 Open
AI & LLM integration patterns easy

How to randomly assign a prompt variant to each key in Python

Randomly pick one variant from a list for each prompt key, useful for A/B testing message variations.

random dictionary a/b-testing
Python
import random

def assign_prompt_variant(prompts: dict[str, list[str]]) -> dict[str, str]:
    """Assign a random prompt variant to each prompt key."""
    return {key: random.choice(variants) for key, variants in prompts.items()}

if __name__ == "__main__":
    prompt_bank = {
        "greeting": ["Hello!", "Hi there…
14 0 Open
Automation & scripting easy

Build a Command-Line Password Generator in Python

Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.

secrets password-generator automation
Python
import secrets
import string

def generate_password(length=16):
    """Generate a cryptographically strong random password."""
    alphabet = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(secrets.choice(alphabet) for _ in range(length))
    return password

if __name__ == "__main__":…
47 0 Open
Automation & scripting easy

Generate Random Fake User Data for Testing in Python

This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.

testing random data-generation
Python
import json
import random
import string
from datetime import datetime, timedelta

def generate_user_data(num_users=1):
    first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
    domains = ["example.com", "test.org", "demo.net"]
    
    users = …
38 0 Open
Automation & scripting easy

Generate Strong Random Passwords with Custom Rules in Python

Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.

password secrets security
Python
import secrets
import string

def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
    pool = ''
    if use_lower:
        pool += string.ascii_lowercase
    if use_upper:
        pool += string.ascii_uppercase
    if use_digits:
        pool += string.digits
    if use_pu…
37 0 Open
Automation & scripting easy

How to Simulate a Traceroute in Python

This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.

traceroute simulation network
Python
import random
import time

def simulate_traceroute(destination, max_hops=30):
    """Simulate a traceroute to a destination with mock hop delays."""
    print(f"Traceroute to {destination} ({max_hops} hops max):")
    for hop in range(1, max_hops + 1):
        # Mock IP address for the hop
        mock_ip = f"10.0.{ra…
15 0 Open
Cloud + Python easy

Generate Mock CloudFormation Stack Events in Python

Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.

cloudformation mock aws
Python
import json
import random
from datetime import datetime, timedelta

def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
    """Generate a list of mock CloudFormation stack events."""
    resources = [
        ("AWS::S3::Bucket", "MyBucket"),
        ("AWS::EC2::Instance", "MyInstance"),
        ("…
15 0 Open
Cloud + Python easy

Pick a Random Region with Mock Carbon Intensity in Python

Selects a random region from a list and generates a mock carbon intensity value using Python's random module.

random mock-data cloud
Python
import random

def pick_region_intensity(regions, seed=42):
    random.seed(seed)
    selected = random.choice(regions)
    intensity = random.randint(1, 10)
    return selected, intensity

if __name__ == "__main__":
    regions = ["North", "South", "East", "West"]
    selected, intensity = pick_region_intensity(regio…
14 0 Open
Modern tooling easy

How to Generate a Mock Rollbar Error Report in Python

Create a realistic fake Rollbar error report with random timestamps, levels, messages, and counts for testing and demos.

rollbar mock-data error-reporting
Python
import json
import random
import time
from datetime import datetime, timedelta


def mock_rollbar_report(n_errors=5):
    messages = [
        "TypeError: unsupported operand type(s) for +: 'int' and 'str'",
        "KeyError: 'user_id'",
        "ValueError: invalid literal for int() with base 10: 'abc'",
        "At…
13 0 Open
Testing & modern typing easy

Fuzz Test Random Bytes Input Crash in Python

A simple fuzz test generates random byte inputs and runs a parser to find unexpected crashes.

fuzzing testing random
Python
import random


def parse_header(data: bytes) -> dict:
    """Parse a fake binary header format."""
    if len(data) < 8:
        raise ValueError("header too short")

    magic = data[:4]
    if magic != b'PARS':
        raise ValueError("bad magic")

    version = data[4]
    if version != 1:
        raise ValueErro…
14 0 Open
System design patterns easy

How to Build a Weighted Random Load Balancer in Python

A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.

python how build
Python
import random
from collections import Counter

SERVERS = {
    "server-a": 50,
    "server-b": 30,
    "server-c": 20,
}


def weighted_random_server(servers: dict[str, int]) -> str:
    """Select a server based on its weight (higher weight = more likely)."""
    total_weight = sum(servers.values())
    rand = random.…
13 0 Open
Streaming & messaging easy

Mock NATS queue group load balancing in Python

Simulates a NATS queue group where each message is delivered to exactly one subscriber using random selection with a lightweight mock.

nats queue-group messaging
Python
import random
import time
from collections import defaultdict


class MockQueueGroup:
    """Mock a NATS queue group: each message is delivered to exactly one subscriber."""

    def __init__(self, subscribers):
        self.subscribers = subscribers

    def publish(self, message):
        receiver = random.choice(se…
13 0 Open
Reliability & rate limiting easy

Chaos Inject Random Failures in Python

Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.

chaos-engineering random resilience
Python
import random


def unreliable_function(success_rate: float = 0.7) -> str:
    """Simulate a function that sometimes fails."""
    if random.random() > success_rate:
        raise ConnectionError("Simulated network failure")
    return "Operation completed successfully"


if __name__ == "__main__":
    random.seed(42)…
15 0 Open
Reliability & rate limiting easy

How to Inject Random Latency for Chaos Testing in Python

Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.

chaos-engineering decorators latency
Python
import random
import time
from functools import wraps

def inject_latency(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        latency = random.uniform(0.1, 0.5)
        print(f"Injecting {latency:.3f}s latency...")
        time.sleep(latency)
        return func(*args, **kwargs)
    return wrapper

@inje…
12 0 Open
Reliability & rate limiting easy

How to Mock Fault Injection Percentage in Python

Simulate a service with a 30% failure rate using random.random to test error handling and retries.

fault-injection random testing
Python
import random

class Service:
    def call(self):
        if random.random() < 0.3:  # 30% failure rate
            raise ConnectionError("Simulated network fault")
        return "ok"

def main():
    svc = Service()
    random.seed(42)  # deterministic for demonstration
    results = []
    for _ in range(10):
     …
14 0 Open
Observability & SRE easy

Generate Mock CPU and Memory Metrics in Python

Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.

mock metrics monitoring
Python
import time
import random


def mock_host_metrics():
    """Generate mock CPU and memory metrics for a host."""
    cpu_percent = round(random.uniform(10.0, 95.0), 1)
    memory_percent = round(random.uniform(20.0, 90.0), 1)
    memory_used_mb = round(random.uniform(512, 8192), 1)

    return {
        "timestamp": in…
15 0 Open
Observability & SRE easy

Generate Synthetic SRE Metrics and Calculate Availability in Python

Create realistic service metrics with random latency, error rate, and request counts, then compute availability and summarize the stream for SLO checks.

sre synthetic-data metrics
Python
from datetime import datetime, timedelta
import random

def generate_service_metrics(service_name: str, minutes: int = 30) -> list[dict]:
    """Generate synthetic SRE metrics for a service across recent minutes."""
    metrics = []
    now = datetime.now()
    
    for i in range(minutes):
        timestamp = now - t…
14 0 Open
Observability & SRE easy

How to Implement Tail Sampling in Python

Sample the slowest subset of calls (tail) for latency analysis using a deque with a random ratio gate.

sampling latency observability
Python
import random
import time
from collections import deque

class TailSampler:
    def __init__(self, tail_ratio=0.1, max_samples=100):
        self.tail_ratio = tail_ratio
        self.max_samples = max_samples
        self.samples = deque(maxlen=max_samples)
        self.total_calls = 0

    def record(self, latency_ms…
13 0 Open
Observability & SRE easy

How to Mock Database Query Duration in Python

Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.

observability mock metrics
Python
import random
import time


def mock_query_duration(db_name, avg_ms, jitter_ms=5, runs=3):
    """Simulate database query durations with realistic variation."""
    durations = []
    for _ in range(runs):
        # Base duration plus random jitter (can be negative)
        duration = avg_ms + random.uniform(-jitter_m…
14 0 Open
Observability & SRE easy

How to Simulate a Queue Depth Gauge in Python

Simulate a queue depth over time using a random enqueue/dequeue process, returning depth values that can be used for monitoring or testing dashboards.

queue simulation monitoring
Python
import collections
import random
import time


def simulate_queue_depth(max_depth=10, steps=20):
    queue = collections.deque()
    depth_history = []

    for _ in range(steps):
        # Randomly enqueue or dequeue
        if random.random() < 0.6 and len(queue) < max_depth:
            queue.append("task")
       …
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.