Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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:
…
How to Shuffle a List in Python
Shuffle a Python list in place or return a new shuffled copy using the random module.
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}")
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.
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…
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.
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…
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.
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…
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.
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…
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.
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__":…
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.
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 = …
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.
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…
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.
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…
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.
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"),
("…
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.
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…
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.
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…
Fuzz Test Random Bytes Input Crash in Python
A simple fuzz test generates random byte inputs and runs a parser to find unexpected crashes.
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…
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.
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.…
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.
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…
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.
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)…
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.
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…
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.
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):
…
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.
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…
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.
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…
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.
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…
How to Mock Database Query Duration in Python
Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.
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…
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.
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")
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.