Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

28 matches
Lists & loops easy

How to Filter a List in Python with a Loop

Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.

filter for-loop lists
Python
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18

adults = []
for age in ages:
    if age >= threshold:
        adults.append(age)

print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
10 0 Open
Functions & basics easy

Python Filter Function with Default Parameters for Beginners

Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.

functions default-parameters filter
Python
def filter_numbers(numbers, threshold=0, reverse=False):
    """Return numbers that pass the threshold filter.

    Args:
        numbers: list of numbers to filter
        threshold: minimum value to keep (default 0)
        reverse: if True, keep numbers below threshold (default False)
    """
    if reverse:
      …
13 0 Open
Files & data easy

Detect Outliers in CSV Data Using Z-Score in Python

Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.

outlier-detection z-score csv
Python
import csv
import statistics
from math import sqrt

def detect_outliers(csv_path, column_name, threshold=2.0):
    """Detect outliers in a numeric column using z-score method."""
    values = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        if column_name not in reader.field…
50 0 Open
Files & data easy

Rotate Log Files in Python by Size

This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.

log-rotation files os
Python
import os
import glob
from pathlib import Path

def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
    log_file = Path(log_path)
    if log_file.stat().st_size <= max_size_bytes:
        print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
        return

    for i in range(max_backu…
13 0 Open
Algorithms & data structures easy

How to Replace Outliers Beyond Threshold with Cap in Python

Replace values that fall below a lower threshold or above an upper threshold by capping them to the threshold values using a simple Python function.

outliers capping data-cleaning
Python
def replace_outliers_with_cap(data, lower_threshold=None, upper_threshold=None):
    """Replace values beyond given thresholds with the threshold values (capping)."""
    if lower_threshold is None and upper_threshold is None:
        raise ValueError("At least one threshold must be provided.")
    
    capped_data = …
12 0 Open
AI & LLM integration patterns easy

How to Build a Simple Semantic Cache for Similar Prompts in Python

Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.

semantic cache prompt matching llm
Python
prompt_cache = [
    "What is the capital of France?",
    "How does recursion work?",
    "Best practices for Python logging?",
    "Explain binary search in one line.",
    "How to reverse a string in Python?"
]

def normalize(text):
    return " ".join(text.lower().split())

def similarity(a, b):
    a_words = set(…
14 0 Open
Automation & scripting easy

Monitor Disk Usage and Alert in Python

A Python script that checks disk usage percentage against a threshold and returns an ALERT or OK message with free space details.

disk monitoring shutil
Python
import shutil
import os

def check_disk_usage(path="/", threshold=85.0):
    usage = shutil.disk_usage(path)
    percent_used = (usage.used / usage.total) * 100
    
    if percent_used > threshold:
        return (f"ALERT: Disk usage at {percent_used:.1f}% on {path} "
                f"(exceeds {threshold}% threshold…
12 0 Open
Data pipelines & processing medium

Check Null Rate Threshold in PySpark DataFrame

This PySpark code checks the null rate of specified DataFrame columns against a threshold and returns violations.

pyspark data quality null check
Python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count

def check_null_rate(df, threshold=0.2, columns=None):
    """
    Check null rate for specified columns (or all) against a threshold.
    Returns columns that exceed the threshold.
    """
    cols = columns or df.columns
    total…
14 0 Open
Data pipelines & processing easy

How to route late-arriving data to a side output in Python

Separate late-arriving events from a streaming data batch into a dead-letter side output list using a timestamp threshold.

data pipelines streaming dead-letter
Python
from collections import defaultdict

def late_arriving_side_output(events, late_threshold_ts):
    """
    Mock a streaming pipeline that separates late-arriving data events
    into a side output list (e.g., for dead-letter analysis).

    events: list of (timestamp, data) tuples, timestamps as ints.
    late_thresho…
12 0 Open
Cloud + Python easy

How to Build a Budget Alert Threshold with Mock Notifications in Python

This code calculates budget usage percentage and triggers a mock alert notification when the usage exceeds a defined threshold.

budget alert threshold
Python
budget = 500.0
spent = 620.0
alert_threshold = 0.8

def mock_notify(percent_used):
    if percent_used >= alert_threshold:
        return f"ALERT: Budget usage at {percent_used * 100:.1f}% — over {alert_threshold * 100:.0f}% threshold!"
    return f"OK: Budget usage at {percent_used * 100:.1f}% — under threshold."

pe…
13 0 Open
Streaming & messaging medium

How to Track Session Windows with Gap Timeout in Python

A Python class that groups events into sessions, closing a session when the gap between events exceeds a timeout threshold.

session-window streaming timeout
Python
import time

class SessionWindow:
    """Track sessions with a gap timeout (mock)."""
    
    def __init__(self, timeout_seconds=5):
        self.timeout = timeout_seconds
        self.session_start = None
        self.last_event_time = None
        self.event_count = 0
        self.events = []
    
    def add_event…
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 medium

Circuit breaker failure threshold count in Python

Track consecutive or time-windowed failures with a deque to open a circuit breaker and auto-recover to half-open after a cooldown.

circuit-breaker resilience deque
Python
from collections import deque
from time import time, sleep


class CircuitBreaker:
    def __init__(self, failure_threshold: int = 5, recovery_time: float = 10.0):
        self.failure_threshold = failure_threshold
        self.recovery_time = recovery_time
        self.failures: deque[float] = deque()
        self.st…
16 0 Open
Reliability & rate limiting medium

Implement a Circuit Breaker Pattern in Python

This code implements a simple circuit breaker that opens after a threshold of consecutive failures, causing subsequent calls to fail fast without invoking the underlying function.

circuit-breaker reliability resilience
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3):
        self.failure_threshold = failure_threshold
        self.failure_count = 0
        self.open = False

    def call(self, func, *args, **kwargs):
        if self.open:
            raise RuntimeError("Circuit is open - failing fast")
        try:
…
15 0 Open
Observability & SRE medium

How to Build a Burn Rate Alert with Multiple Time Windows in Python

Track token consumption and trigger alerts when the burn rate exceeds a threshold across multiple time windows using deque and time-based sliding windows.

burn-rate alerts time-windows
Python
import time
from collections import deque

class BurnRateAlert:
    def __init__(self, windows_seconds=(60, 300, 900), threshold_rate=0.8):
        self.windows = {w: deque() for w in windows_seconds}
        self.threshold_rate = threshold_rate
        self.previous_tokens = None

    def record_sample(self, current_…
16 0 Open
Observability & SRE easy

How to mock Prometheus alert rule thresholds in Python

Simulate a Prometheus alert rule with a configurable threshold and duration window, firing only when the metric exceeds the threshold long enough.

prometheus alerting sre
Python
import time
import random


class MetricsStore:
    def __init__(self):
        self.metrics = {}

    def set_metric(self, name, value, labels=None):
        key = (name, tuple(sorted((labels or {}).items())))
        self.metrics[key] = value

    def get_metric(self, name, labels=None):
        key = (name, tuple(s…
14 0 Open
Observability & SRE easy

Rotate Log Files by Size in Python

A mock log rotation script that renames log files exceeding a size threshold, appending numbered backups.

log-rotation pathlib file-management
Python
import os
from pathlib import Path

def rotate_logs(directory: str, max_size: int = 100) -> None:
    """Rotate log files that exceed max_size bytes."""
    log_dir = Path(directory)
    for log_file in sorted(log_dir.glob("*.log"), key=lambda p: str(p)):
        if log_file.stat().st_size > max_size:
            for …
13 0 Open
Microservices patterns medium

How to implement a circuit breaker in Python

A Python CircuitBreaker class that tracks failures, opens after a threshold, and retries after a timeout.

circuit-breaker resilience microservices
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout=5):
        self.failure_threshold = failure_threshold
        self.timeout = timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "CLOSED"

    def call(self, mock_downstream):
        if self.state …
13 0 Open
Big data & Spark easy

Session window gap mock in Python

Group sorted timestamps into sessions where any gap between consecutive events exceeds a threshold starts a new session.

timestamps sessions windowing
Python
from datetime import datetime, timedelta


def session_windows(timestamps, gap_seconds=300):
    """Group timestamps into sessions where gaps > gap_seconds start new sessions."""
    if not timestamps:
        return []

    # Sort timestamps chronologically to ensure correct windowing
    timestamps = sorted(timestam…
14 0 Open
ML engineering pipelines medium

Detect Concept Drift in Python with a Simple Statistical Test

Detect concept drift by comparing the mean of recent data against a reference distribution using a z-score-like threshold.

concept drift statistics ml monitoring
Python
import random
import statistics

def detect_drift(recent, reference, threshold=1.5):
    ref_mean = statistics.mean(reference)
    ref_std = statistics.stdev(reference)
    
    recent_mean = statistics.mean(recent)
    drift_score = abs(recent_mean - ref_mean) / (ref_std if ref_std > 0 else 1)
    
    drifted = drif…
15 0 Open
ML engineering pipelines easy

How to Trigger Model Retraining on Drift in Python

Automatically detects accuracy drift in a mock ML model and triggers retraining when performance falls below a threshold.

ml drift-detection retraining
Python
import random
import time

class MockModel:
    def __init__(self, name):
        self.name = name
        self.accuracy = 0.85
        self.version = 1

    def train(self, data_size):
        # Simulate training time and accuracy improvement
        time.sleep(0.1)
        drift = random.uniform(-0.02, 0.02)
       …
16 0 Open
ML engineering pipelines easy

How to do feature selection with VarianceThreshold in Python

This code demonstrates how to use scikit-learn's VarianceThreshold to remove low-variance features from a NumPy array, keeping only those that vary enough to be useful for modeling.

feature selection sklearn machine learning
Python
import numpy as np
from sklearn.feature_selection import VarianceThreshold

def main():
    # Mock dataset: 4 samples, 5 features
    X = np.array([
        [0.1, 0.2, 1.0, 1.0, 0.5],
        [0.2, 0.2, 0.0, 1.0, 0.4],
        [0.1, 0.2, 1.0, 1.0, 0.6],
        [0.3, 0.2, 1.0, 0.0, 0.5]
    ])

    # Select features w…
14 0 Open
A/B testing & experimentation easy

How to Build a Guardrail Metrics Monitor in Python

This code implements a mock monitor that records metric values, checks them against thresholds, and summarizes pass/alert statistics.

metrics monitoring ab-testing
Python
import random
import time
from collections import defaultdict


class GuardrailMetricsMonitor:
    def __init__(self):
        self.metrics = defaultdict(list)
        self.thresholds = {
            "prompt_toxicity": 0.8,
            "response_length": 500,
            "latency_ms": 1000,
        }

    def record(s…
15 0 Open
Database scaling & optimization medium

How to Mock a Hot Shard Split in Python

Simulate a database hot shard splitting into two shards by key ranges when it exceeds a threshold, with a mock class for testing.

sharding databases mock
Python
import random
from collections import defaultdict


class HotShardMock:
    """Mock implementation of a hot shard split in a distributed database."""

    def __init__(self, shard_id="shard_1", max_entries=5):
        self.shard_id = shard_id
        self.max_entries = max_entries
        self.entries = {}

    def ad…
16 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.