Claude Code for sortedcontainers: Sorted Data Structures in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for sortedcontainers: Sorted Data Structures in Python
AI

Claude Code for sortedcontainers: Sorted Data Structures in Python

Published: April 16, 2028
Read time: 5 min read
By: Claude Skills 360

sortedcontainers provides pure-Python sorted list, dict, and set that maintain order on insert/delete. pip install sortedcontainers. SortedList: from sortedcontainers import SortedList; sl = SortedList([3,1,2]); sl[1,2,3]. Add: sl.add(1.5). Discard: sl.discard(2). Index: sl[0], sl[-1]. Count: sl.count(1). Bisect: sl.bisect_left(2), sl.bisect_right(2). Range: sl.irange(2, 5) → iterator of 2 <= x <= 5. Islice: sl.islice(0, 3) — index slice. Pop: sl.pop(0) — pop by index. Update: sl.update([4,5,6]). SortedKeyList: SortedKeyList(key=abs) — sort by abs value. SortedDict: from sortedcontainers import SortedDict; sd = SortedDict({"b":2,"a":1}); list(sd)["a","b"]. sd.peekitem(0), sd.peekitem(-1). sd.keys() — sorted. sd.irange("a","c"). sd.popitem(last=False) — FIFO. SortedSet: from sortedcontainers import SortedSet; ss = SortedSet([3,1,2,1]){1,2,3}. ss.bisect(3). ss.irange(1,3). ss.pop(0). ss.update([4,5]). All three support len(), in, iter, reversed(), slice. Performance: O(log n) add/discard; O(√n) indexing — faster than sorted(list) for dynamic workloads. Key: SortedList(key=fn) → sort by derived value. Claude Code generates sortedcontainers leaderboards, time-ordered event queues, and range-query data structures.

CLAUDE.md for sortedcontainers

## sortedcontainers Stack
- Version: sortedcontainers >= 2.4 | pip install sortedcontainers
- SortedList: maintains sorted order on add/discard | bisect_left/right | irange
- SortedKeyList: SortedList(key=fn) — sort by derived value not raw value
- SortedDict: dict with keys in sorted order | peekitem(0) | irange | popitem
- SortedSet: set with sorted iteration | bisect | irange | union/intersection
- All: O(log n) add/discard | O(√n) index access | supports slicing + iter

sortedcontainers Data Structure Pipeline

# app/sorted_utils.py — SortedList, SortedDict, SortedSet, leaderboard, event queue
from __future__ import annotations

import heapq
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable, Iterator

from sortedcontainers import SortedDict, SortedKeyList, SortedList, SortedSet


# ─────────────────────────────────────────────────────────────────────────────
# 1. SortedList helpers
# ─────────────────────────────────────────────────────────────────────────────

def sorted_insert(sl: SortedList, item: Any) -> int:
    """Insert item; return insertion index."""
    idx = sl.bisect_left(item)
    sl.add(item)
    return idx


def rank(sl: SortedList, value: Any) -> int:
    """
    Return the 0-based rank of value in a sorted list (ascending).
    Values smaller than value have lower rank.
    """
    return sl.bisect_left(value)


def percentile(sl: SortedList, p: float) -> Any:
    """
    Return the p-th percentile value (p in [0, 1]).
    Requires at least one element.
    """
    idx = max(0, min(len(sl) - 1, int(p * len(sl))))
    return sl[idx]


def range_query(sl: SortedList, lo: Any, hi: Any, inclusive: bool = True) -> list:
    """Return all items in sl where lo <= x <= hi (or lo <= x < hi)."""
    if inclusive:
        return list(sl.irange(lo, hi))
    return list(sl.irange(lo, hi, inclusive=(True, False)))


def nearest(sl: SortedList, value: Any) -> Any | None:
    """Return the item in sl closest to value."""
    if not sl:
        return None
    idx = sl.bisect_left(value)
    candidates = []
    if idx < len(sl):
        candidates.append(sl[idx])
    if idx > 0:
        candidates.append(sl[idx - 1])
    return min(candidates, key=lambda x: abs(x - value))


def median(sl: SortedList) -> float:
    """Return median of a non-empty SortedList."""
    n = len(sl)
    if n == 0:
        raise ValueError("Cannot compute median of empty SortedList")
    mid = n // 2
    if n % 2 == 1:
        return sl[mid]
    return (sl[mid - 1] + sl[mid]) / 2.0


# ─────────────────────────────────────────────────────────────────────────────
# 2. SortedDict helpers
# ─────────────────────────────────────────────────────────────────────────────

def min_key(sd: SortedDict) -> Any:
    """Return smallest key without removing it."""
    return sd.peekitem(0)[0]


def max_key(sd: SortedDict) -> Any:
    """Return largest key without removing it."""
    return sd.peekitem(-1)[0]


def keys_in_range(sd: SortedDict, lo: Any, hi: Any) -> list:
    """Return all keys where lo <= key <= hi."""
    return list(sd.irange(lo, hi))


def items_in_range(sd: SortedDict, lo: Any, hi: Any) -> list[tuple]:
    """Return all (key, value) pairs where lo <= key <= hi."""
    return [(k, sd[k]) for k in sd.irange(lo, hi)]


def pop_min(sd: SortedDict) -> tuple:
    """Remove and return the (smallest_key, value) pair."""
    return sd.popitem(0)


def pop_max(sd: SortedDict) -> tuple:
    """Remove and return the (largest_key, value) pair."""
    return sd.popitem(-1)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Leaderboard
# ─────────────────────────────────────────────────────────────────────────────

class Leaderboard:
    """
    High-score leaderboard backed by SortedDict and SortedKeyList.
    Supports O(log n) insert and top-n queries.

    Usage:
        lb = Leaderboard()
        lb.submit("Alice", 1500)
        lb.submit("Bob",   1200)
        lb.submit("Alice", 1800)   # updates Alice's best score
        print(lb.top(3))
    """

    def __init__(self):
        self._scores: dict[str, int] = {}          # player → best score
        self._ranked: SortedList = SortedList()    # (-score, player) for desc order

    def submit(self, player: str, score: int) -> None:
        """Record a score for player; keeps best score only."""
        if player in self._scores:
            old = self._scores[player]
            self._ranked.discard((-old, player))
        self._scores[player] = score
        self._ranked.add((-score, player))

    def score(self, player: str) -> int | None:
        """Return player's best score or None."""
        return self._scores.get(player)

    def rank(self, player: str) -> int | None:
        """Return 1-based rank of player (1 = top scorer) or None."""
        if player not in self._scores:
            return None
        s = self._scores[player]
        return self._ranked.bisect_left((-s, player)) + 1

    def top(self, n: int) -> list[tuple[str, int]]:
        """Return top n players as [(player, score), ...] descending."""
        return [(p, -s) for s, p in self._ranked[:n]]

    def all_ranked(self) -> list[tuple[str, int]]:
        """Return all players in rank order."""
        return [(p, -s) for s, p in self._ranked]

    def __len__(self) -> int:
        return len(self._scores)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Time-ordered event log
# ─────────────────────────────────────────────────────────────────────────────

@dataclass(order=True)
class Event:
    timestamp: float
    data: Any = field(compare=False)


class EventLog:
    """
    Append-only event log backed by SortedList.
    Supports O(log n) insert and range-time queries.

    Usage:
        log = EventLog()
        log.append("user.login", user_id=1)
        events = log.range_query(start, end)
    """

    def __init__(self):
        self._events: SortedList = SortedList(key=lambda e: e.timestamp)

    def append(self, event_type: str, **kwargs) -> Event:
        """Append a new event with current timestamp."""
        e = Event(timestamp=time.time(), data={"type": event_type, **kwargs})
        self._events.add(e)
        return e

    def range_query(self, start: float, end: float) -> list[Event]:
        """Return all events where start <= timestamp <= end."""
        # Build sentinel Events for bisect comparison
        left = Event(timestamp=start, data=None)
        right = Event(timestamp=end, data=None)
        lo = self._events.bisect_left(left)
        hi = self._events.bisect_right(right)
        return list(self._events.islice(lo, hi))

    def recent(self, n: int) -> list[Event]:
        """Return last n events."""
        return list(self._events[-n:])

    def __len__(self) -> int:
        return len(self._events)


# ─────────────────────────────────────────────────────────────────────────────
# 5. Running statistics tracker
# ─────────────────────────────────────────────────────────────────────────────

class RunningStats:
    """
    Tracks a stream of numeric values.
    Computes median, percentile, and rank queries in O(log n).

    Usage:
        stats = RunningStats()
        for v in sensor_readings:
            stats.add(v)
        print(stats.median(), stats.percentile(0.95))
    """

    def __init__(self):
        self._sl: SortedList = SortedList()
        self._total: float = 0.0

    def add(self, value: float) -> None:
        self._sl.add(value)
        self._total += value

    def median(self) -> float:
        return median(self._sl)

    def mean(self) -> float:
        if not self._sl:
            raise ValueError("No data")
        return self._total / len(self._sl)

    def percentile(self, p: float) -> float:
        return percentile(self._sl, p)

    def rank(self, value: float) -> int:
        return rank(self._sl, value)

    def range_count(self, lo: float, hi: float) -> int:
        """Count values where lo <= val <= hi."""
        return self._sl.bisect_right(hi) - self._sl.bisect_left(lo)

    def __len__(self) -> int:
        return len(self._sl)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== SortedList basics ===")
    sl = SortedList([5, 2, 8, 1, 9, 3])
    print("sorted:", list(sl))
    sl.add(4.5)
    print("after add(4.5):", list(sl))
    print("bisect_left(5):", sl.bisect_left(5))
    print("range [3,7]:    ", range_query(sl, 3, 7))
    print("nearest(6):     ", nearest(sl, 6))
    print("median:         ", median(sl))
    print("p90:            ", percentile(sl, 0.9))

    print("\n=== SortedDict ===")
    sd = SortedDict({"cherry": 3, "apple": 1, "banana": 2, "date": 4})
    print("keys in order:", list(sd.keys()))
    print("min/max key:  ", min_key(sd), "/", max_key(sd))
    print("range [b,c]:  ", keys_in_range(sd, "banana", "cherry"))
    print("items [a,c]:  ", items_in_range(sd, "apple", "cherry"))

    print("\n=== Leaderboard ===")
    lb = Leaderboard()
    scores = [("Alice",1500),("Bob",1200),("Carol",1800),("Alice",1900),("Dave",1100),("Bob",1600)]
    for player, score in scores:
        lb.submit(player, score)
    print("top 3:", lb.top(3))
    print("Alice rank:", lb.rank("Alice"))
    print("Bob score: ", lb.score("Bob"))

    print("\n=== RunningStats ===")
    import random
    random.seed(42)
    stats = RunningStats()
    for _ in range(1000):
        stats.add(random.gauss(100, 15))
    print(f"n={len(stats)}  mean={stats.mean():.1f}  median={stats.median():.1f}")
    print(f"p90={stats.percentile(0.90):.1f}  p95={stats.percentile(0.95):.1f}")
    print(f"values in [90,110]: {stats.range_count(90, 110)}")

    print("\n=== SortedSet ===")
    ss1 = SortedSet([3, 1, 4, 1, 5, 9, 2, 6])
    ss2 = SortedSet([2, 4, 6, 8])
    print("ss1:          ", list(ss1))
    print("intersection: ", list(ss1 & ss2))
    print("union:        ", list(ss1 | ss2))
    print("bisect(5):    ", ss1.bisect(5))
    print("irange(3,7):  ", list(ss1.irange(3, 7)))

For the heapq stdlib alternative — heapq is a min-heap that gives O(log n) push/pop but only supports pop-min, no arbitrary index access, no range queries, and no sorted iteration over all elements; sortedcontainers SortedList supports add/discard/in/bisect/index/irange all in one structure with a clean Python list-like API. For the bisect stdlib alternative — bisect maintains sorted order via binary search on a plain list but mutating a plain list (insert, delete) is O(n); sortedcontainers SortedList maintains O(log n) for both add and discard without the O(n) cost, and adds irange, islice, and SortedKeyList. The Claude Skills 360 bundle includes sortedcontainers skill sets covering SortedList add/discard/bisect/irange/islice, rank()/percentile()/median()/nearest()/range_query() helpers, SortedDict peekitem/irange/pop_min/pop_max, SortedSet union/intersection/irange, Leaderboard (O(log n) submit/rank/top), EventLog time-range queries, and RunningStats stream analytics. Start with the free tier to try sorted data structure code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free