Reference library

Python Code Samples

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

30 matches
Lists & loops easy

How to Truncate a List to Max Length in Python (Keep Head)

This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.

list slicing truncate
Python
from typing import List

def truncate_head(lst: List[object], max_length: int) -> List[object]:
    """Return a new list with at most max_length items from the head."""
    if max_length < 0:
        raise ValueError("max_length must be non-negative")
    return lst[:max_length]

if __name__ == "__main__":
    # Examp…
14 0 Open
Files & data easy

Export List of Dicts to CSV in Python

Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.

csv export dictwriter
Python
import csv

def export_to_csv(data, filename):
    """Export a list of dicts to a CSV file."""
    if not data:
        print("No data to export")
        return
    
    # Get column names from the keys of the first dict
    fieldnames = list(data[0].keys())
    
    with open(filename, 'w', newline='', encoding='utf…
14 0 Open
Files & data easy

Export SQLite Query Results to CSV in Python

Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.

sqlite csv export
Python
import sqlite3
import csv

def export_query_to_csv(db_path, query, csv_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(query)

    rows = cursor.fetchall()
    column_names = [description[0] for description in cursor.description]

    with open(csv_path, 'w', newline='', encodi…
17 0 Open
Files & data easy

How to Convert CSV Column Types While Reading in Python

Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.

csv type-conversion file-io
Python
import csv
from pathlib import Path
from typing import Any

def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
    """Read CSV and convert column types based on header suffixes."""
    converters = {
        "int": int,
        "float": float,
        "str": str,
        "bool": lambda v: v.strip().lower(…
11 0 Open
Files & data easy

How to Read Binary File Bytes and Inspect the Header in Python

Read the first bytes of a binary file with pathlib and display them as a hex dump plus an ASCII view to inspect file headers.

binary file-io hex
Python
import pathlib

def inspect_binary_header(filepath: str, num_bytes: int = 16) -> None:
    """Read the first bytes of a binary file and display them as hex and ASCII."""
    path = pathlib.Path(filepath)
    data = path.read_bytes()[:num_bytes]
    
    hex_str = ' '.join(f"{byte:02x}" for byte in data)
    ascii_str …
12 0 Open
Files & data easy

Normalize CSV Column Names to snake_case in Python

Convert CSV header names to snake_case using a regular expression and write the updated file in place.

csv regex snake-case
Python
import csv
import re
import sys


def to_snake_case(header):
    header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
    header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
    return header


def normalize_csv_headers(input_path, output_path=None):
    with open(input_path, newline="", encoding="utf…
13 0 Open
Files & data easy

Split CSV Files into Smaller Chunks in Python

Splits a large CSV file into multiple smaller chunk files, preserving the header row in each chunk.

csv file-splitting batch-processing
Python
import csv
import os

def split_csv(input_file, chunk_size=1000, output_prefix="chunk"):
    """Split a large CSV file into smaller chunks."""
    with open(input_file, 'r', newline='') as infile:
        reader = csv.reader(infile)
        header = next(reader)
        
        file_count = 1
        row_count = 0
  …
44 0 Open
Files & data easy

Write CSV file with csv DictWriter in Python

Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.

csv file-writing dictwriter
Python
import csv
from pathlib import Path

fieldnames = ["name", "city", "age"]
rows = [
    {"name": "Alice", "city": "New York", "age": 30},
    {"name": "Bob", "city": "Los Angeles", "age": 25},
    {"name": "Charlie", "city": "Chicago", "age": 35},
]

path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
16 0 Open
OOP & classes easy

Slots Class: How to Reduce Memory Usage in Python

Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.

memory slots class
Python
class SlotsDemo:
    __slots__ = ("name", "age", "email")

    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email

    def describe(self):
        return f"{self.name}, {self.age}, {self.email}"

if __name__ == "__main__":
    instance = SlotsDemo("Alice", …
12 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Automation & scripting easy

How to Create a Mock Headless Browser Screenshot Stub in Python

This code provides a deterministic stub that simulates capturing webpage screenshots with a headless browser, returning formatted output without real browser dependencies.

mock headless screenshot
Python
import subprocess
import sys

def mock_screenshot_webpage(url: str, width: int = 1280, height: int = 800) -> str:
    """Stub that simulates taking a screenshot of a webpage using headless browser."""
    # In real implementation, you would use playwright/selenium/headless chrome
    result = {
        "url": url,
   …
13 0 Open
Git + Python easy

How to List Changed Files in the Last Git Commit with Python

Runs `git diff --name-only HEAD~1 HEAD` via subprocess to list the names of files changed in the most recent commit.

git subprocess automation
Python
import subprocess

def list_changed_files():
    result = subprocess.run(
        ["git", "diff", "--name-only", "HEAD~1", "HEAD"],
        capture_output=True,
        text=True,
        check=True
    )
    files = result.stdout.strip().splitlines()
    return files

if __name__ == "__main__":
    changed = list_cha…
14 0 Open
Git + Python easy

How to Revert a Commit and Create a New Revert Commit in Python

Demonstrates a mock Git repository that creates a new revert commit on top of the current head when reverting an existing commit.

git revert mock
Python
class GitCommit:
    """Minimal mock of a git commit for demonstrating revert behavior."""
    def __init__(self, sha, message):
        self.sha = sha
        self.message = message
        self.parent = None


class GitRepository:
    """Mock repository tracking a simple commit chain."""
    def __init__(self):
    …
13 0 Open
Cloud + Python easy

Generate an Idempotency-Key header mock with UUID in Python

This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.

uuid idempotency mock
Python
import uuid

class MockIdempotencyService:
    def __init__(self):
        self._tokens = {}

    def get_token(self, header_name="Idempotency-Key"):
        token = str(uuid.uuid4())
        self._tokens[header_name] = token
        return token

    def validate(self, header_name="Idempotency-Key"):
        return s…
11 0 Open
Cloud + Python easy

How to plan reserved capacity from a CSV in Python

Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.

csv capacity-planning cloud
Python
import csv
import io


def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
    """Read a CSV of workloads and return a plan for reserved capacity per service."""
    reader = csv.DictReader(io.StringIO(workloads_csv))
    plan = []
    for row in reader:
        service = row["service"]
        avg_load = fl…
11 0 Open
Modern tooling easy

Build a Textual TUI App Skeleton in Python

Create a minimal Textual terminal UI app with a header, label, button, and footer, ready for interactive mock demonstrations.

textual tui terminal
Python
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Button, Label

class MockApp(App):
    """A minimal Textual TUI app skeleton."""

    BINDINGS = [("q", "quit", "Quit")]

    def compose(self) -> ComposeResult:
        """Create child widgets."""
        yield Header()
        yie…
15 0 Open
System design patterns easy

Create a Data Helper Class in Python

A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.

data-helper json csv
Python
import json
import csv
from pathlib import Path

class DataHelper:
    def __init__(self, base_path="."):
        self.base_path = Path(base_path)
        self.base_path.mkdir(exist_ok=True)

    def save_json(self, data, filename):
        path = self.base_path / filename
        with open(path, "w") as f:
          …
15 0 Open
API design & gRPC easy

How to Add a Correlation ID Tracing Header in Python

A mock middleware generates or preserves a correlation ID header and logs structured JSON messages with it for API request tracing.

correlation-id tracing middleware
Python
import uuid
import json
from dataclasses import dataclass, field
from typing import Optional

@dataclass
class Request:
    headers: dict = field(default_factory=dict)

    def get(self, key, default=None):
        return self.headers.get(key, default)

class CorrelationIdMiddleware:
    def __init__(self, header_name…
16 0 Open
API design & gRPC easy

How to Decode Basic Auth Credentials in Python

Decode username and password from a Basic Auth header string using base64 and standard string operations.

base64 authentication api
Python
import base64

def decode_basic_auth(header_value):
    """
    Decode credentials from a Basic Auth header value.
    
    Expected format: "Basic base64encoded(username:password)"
    Returns a tuple (username, password).
    """
    if not header_value.startswith("Basic "):
        raise ValueError("Invalid Basic A…
13 0 Open
API design & gRPC easy

How to Mock Content-Disposition and Extract Filename in Python

Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.

http mocking regex
Python
import os
from pathlib import Path
import re
from unittest.mock import patch

def get_filename_from_content_disposition(header_value):
    """
    Extract filename from a Content-Disposition header value.
    Supports both filename and filename* parameters (RFC 5987).
    """
    if not header_value:
        return No…
15 0 Open
API design & gRPC easy

How to Mock an API Key Header Authentication Server in Python

A minimal HTTP server that validates requests using an X-API-Key header and returns JSON responses for authenticated and unauthenticated calls.

api authentication http
Python
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

API_KEYS = {"test-user": "secret-key-123"}

class AuthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        auth = self.headers.get("X-API-Key")
        if not auth or auth not in API_KEYS.values():
            self.send_response…
12 0 Open
API design & gRPC easy

How to handle CORS preflight OPTIONS requests in Python

Create a mock HTTP server with a CORS preflight OPTIONS handler that returns the correct headers for browser-based API requests.

cors http server
Python
from http.server import BaseHTTPRequestHandler, HTTPServer

class CORSRequestHandler(BaseHTTPRequestHandler):
    def _send_cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        self.send_head…
13 0 Open
Observability & SRE easy

How to Generate and Propagate W3C Trace Context Headers in Python

Generate and propagate W3C traceparent and tracestate headers for distributed tracing in Python, with mock service headers.

observability tracing w3c
Python
import uuid


def generate_w3c_traceparent(trace_id=None, parent_id=None, flags="01"):
    if trace_id is None:
        trace_id = uuid.uuid4().hex[:32]
    if parent_id is None:
        parent_id = uuid.uuid4().hex[:16]
    return f"00-{trace_id}-{parent_id}-{flags}"


def create_mock_headers(service_name, trace_id=N…
12 0 Open
Observability & SRE easy

How to Simulate Trace Sampling Head in Python

Simulate head-based probabilistic trace sampling on mock trace data with a configurable sample rate and optional seed for reproducibility.

tracing sampling observability
Python
import random

def trace_sampling_head(mock_traces, sample_rate=0.5, seed=None):
    """Simulate probabilistic trace sampling (head-based) on mock data.
    
    Args:
        mock_traces: list of trace dictionaries with a unique 'trace_id'
        sample_rate: float 0.0-1.0, probability of keeping a trace
        see…
12 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.