Reference library

Python Code Samples

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

12 matches
Algorithms & data structures easy

How to Find Gaps Between Sorted Intervals in Python

This code finds gap ranges between sorted intervals using pairwise iteration, returning ranges where no interval covers.

intervals pairwise sorting
Python
from itertools import pairwise

def find_gaps(intervals):
    intervals = sorted(intervals)
    gaps = []
    for prev, curr in pairwise(intervals):
        if prev[1] < curr[0]:
            gaps.append((prev[1] + 1, curr[0] - 1))
    return gaps

if __name__ == "__main__":
    intervals = [(1, 3), (5, 7), (10, 12), (…
14 0 Open
Algorithms & data structures easy

How to compress consecutive numbers into range strings in Python

Convert a sorted list of consecutive integers into compact range strings like '1-3', '5-6', and '15'.

ranges compression arrays
Python
def compress_ranges(nums):
    """Convert a list of sorted consecutive numbers into range strings."""
    if not nums:
        return []
    
    ranges = []
    start = prev = nums[0]
    
    for num in nums[1:]:
        if num == prev + 1:
            prev = num
        else:
            if start == prev:
         …
15 0 Open
Algorithms & data structures easy

Rearrange array alternately max min in Python

Rearranges a sorted list so its elements alternate between the current maximum and current minimum using two pointers in O(n) time.

two-pointers array sorting
Python
def rearrange_alternately(arr):
    """
    Rearrange sorted array so elements alternate: max, min, next max, next min...
    Returns a new list in O(n) time using O(n) space.
    """
    n = len(arr)
    result = []
    left, right = 0, n - 1
    while left <= right:
        if left == right:
            result.appen…
14 0 Open
Automation & scripting easy

How to Split PDF Pages into Ranges in Python

Simulates splitting a PDF into page ranges by validating and returning structured range splits for automation workflows.

pdf automation file-processing
Python
import os

def split_pdf_ranges(pdf_name, num_pages, ranges):
    """
    Simulates splitting a PDF by returning the page ranges that would be split.

    Args:
        pdf_name (str): Name of the PDF file.
        num_pages (int): Total number of pages in the PDF.
        ranges (list of tuple): List of (start, end) …
12 0 Open
Automation & scripting easy

How to Write an IP Block List to hosts.deny in Python

This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.

hosts.deny ip-block ipaddress
Python
from ipaddress import ip_network

def write_hosts_deny(ip_list, output_file="hosts.deny"):
    with open(output_file, "w") as f:
        for ip in ip_list:
            try:
                ip_network(ip)
                f.write(f"ALL: {ip}\n")
            except ValueError:
                continue
    print(f"Written…
14 0 Open
Data pipelines & processing easy

How to Filter Data in Python

Filter a list of dictionaries by exact key-value matches or numerical ranges using concise list comprehensions.

filtering list-comprehension dictionaries
Python
from typing import List, Dict, Any


def filter_data(
    data: List[Dict[str, Any]], key: str, value: Any
) -> List[Dict[str, Any]]:
    """Return records where data[key] equals value."""
    return [record for record in data if record.get(key) == value]


def filter_by_range(
    data: List[Dict[str, Any]], key: str…
12 0 Open
Cloud + Python easy

How to Validate AWS Security Group Ingress Rules in Python

Validates AWS security group ingress rules (protocol, port ranges, CIDR, description) and returns a list of errors or OK.

aws security-groups validation
Python
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class SecurityGroupRule:
    protocol: str
    port_range: tuple
    cidr: str
    description: str = ""

def validate_ingress_rule(rule: SecurityGroupRule) -> List[str]:
    """Validate a security group ingress rule against common AWS pat…
11 0 Open
API design & gRPC easy

How to Validate Data in Python for Beginners

A beginner-friendly Python class for validating required fields, types, ranges, and allowed choices in dict payloads.

validation data api
Python
import json
from typing import Any, Dict, List, Optional, Union


class Validator:
    """A simple validate data helper designed for beginners."""

    def __init__(self, data: Union[Dict[str, Any], List[Any]]):
        self.data = data
        self.errors: Dict[str, str] = {}

    def validate_required(self, field: s…
13 0 Open
Observability & SRE easy

How to Link Parent and Child Span Elements in Python

This code defines a lightweight mock element class and a function that links child elements to a parent when their ranges are nested within the parent's range.

spans nesting mock
Python
class MockElement:
    def __init__(self, name, start, end, children=None):
        self.name = name
        self.start = start
        self.end = end
        self.children = children or []

    def __repr__(self):
        return f"MockElement({self.name}, {self.start}-{self.end})"


def link_parent_child(parent, chil…
14 0 Open
Observability & SRE easy

How to Mock HTTP Client Latency in Python

Simulate outbound HTTP request latency with configurable ranges to test timeouts, retries, and SLO monitoring without external services.

latency mocking http-client
Python
import time
import random

def mock_latency(host: str, min_ms: int = 100, max_ms: int = 500) -> dict:
    """Simulate an outbound HTTP request with mock latency."""
    latency_ms = random.randint(min_ms, max_ms)
    start = time.perf_counter()
    time.sleep(latency_ms / 1000)
    elapsed_ms = (time.perf_counter() - …
14 0 Open
Database scaling & optimization easy

How to Mock Date Sharding by Range in Python

Split a date interval into fixed-size contiguous shards, returning each window as an ISO date string pair.

date datetime sharding
Python
from datetime import date, timedelta

def shard_ranges(start_date, end_date, shard_days=7):
    if start_date > end_date:
        raise ValueError("start_date cannot be after end_date")

    shards = []
    current = start_date
    while current <= end_date:
        shard_end = min(current + timedelta(days=shard_days …
13 0 Open
Database scaling & optimization easy

Rebalance Shard Ranges Across Nodes in Python

A mock rebalancing function that shuffles shard ranges and distributes them evenly across nodes using round-robin assignment.

sharding rebalancing dataclass
Python
import random
from dataclasses import dataclass

@dataclass
class Shard:
    id: int
    start: int
    end: int

def rebalance_shards(shards: list[Shard], node_count: int) -> dict[int, list[Shard]]:
    """Mock rebalancing of shard ranges across nodes."""
    all_ranges = [(s.start, s.end) for s in shards]
    random…
11 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.