Reference library

Python Code Samples

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

51 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 medium

Create a Python Tool That Generates Professional Excel Dashboards

Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.

openpyxl excel dashboard
Python
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

def create_sales_dashboard(workbook_path: str) -> None:
    """Generate a professional sales dashboard in an Excel workbook."""
    wb = op…
49 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 medium

Generate a Monthly Calendar PDF in Python

Create a Python utility that generates a monthly calendar PDF using ReportLab, with weekday headers and day numbers laid out in a grid.

calendar pdf reportlab
Python
from calendar import TextCalendar
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os

def generate_monthly_calendar_pdf(year, month, filename="calendar.pdf"):
    cal = TextCalendar()
    days = cal.monthdays2calendar(year, month)
    
    month_name …
1767 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(…
12 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 medium

How to Scrape Headlines from a News Website Using Beautiful Soup in Python

Scrape headline text from a news website using requests and Beautiful Soup with a CSS selector.

web scraping beautifulsoup requests
Python
import requests
from bs4 import BeautifulSoup

def scrape_headlines(url: str, selector: str) -> list:
    """
    Scrape headlines from a news website using Beautiful Soup.
    
    Args:
        url: The URL of the news website.
        selector: CSS selector for headline elements.
    
    Returns:
        List of h…
57 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 medium

Automatically Generate Charts from CSV Files with One Command

Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.

csv matplotlib charting
Python
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt

def generate_chart(csv_path: str) -> None:
    """Read a CSV file with headers and plot the first two numeric columns."""
    data = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.reader(f)
        headers = next(re…
65 0 Open
Automation & scripting medium

Build a Website Accessibility Scanner Using Python

Scans a webpage for common accessibility issues like missing alt text, headings, labels, and landmarks using only Python.

accessibility a11y html
Python
import requests
from urllib.parse import urljoin
from html.parser import HTMLParser
import re

class AccessibilityParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.images_without_alt = []
        self.missing_headings = True
        self.has_main_tag = False
        self.label_for_inp…
40 0 Open
Automation & scripting medium

Create a Python Script That Detects Website Technology Stack Automatically

This script sends an HTTP request to a URL and inspects headers and HTML content to identify technologies like servers, frameworks, and JavaScript libraries.

requests web scraping tech stack
Python
import requests
from re import search

def detect_tech_stack(url):
    tech_stack = []
    try:
        response = requests.get(url, timeout=5, headers={'User-Agent': 'Mozilla/5.0'})
        headers = response.headers
        html = response.text.lower() if response.text else ''

        # Check server header
        …
43 0 Open
Automation & scripting medium

Find Broken Image References Across a Website in Python

Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.

web scraping crawling broken links
Python
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed

def find_all_links(base_url, max_pages=50):
    visited, to_visit = set(), {base_url}
    while to_visit and len(visited) < max_pages:
        url = to_visit.pop()
 …
39 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

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.