A sorted list can answer a surprisingly wrong question very quickly. Suppose its keys are 10, 20, 20, 20, and 35. Searching for 20 might mean finding the first matching record, returning all three matches, selecting the last observation at or below 20, or starting a window that includes 20 and excludes 35. Each request has a different boundary contract. A plausible implementation can pass examples with unique values while silently choosing the wrong record when duplicates arrive.

This tutorial builds a small, immutable sorted snapshot for those questions. The example uses integer keys and labeled records so that duplicate behavior stays visible. We will separate insertion positions from confirmed matches, derive half-open range queries, define floor and ceiling ties, and compare the implementation with simple linear reference calculations. DeepSeek appears as an optional reviewer of a written contract. The review prompts are unexecuted templates; no DeepSeek API run or model-generated test result is claimed.

The central design choice is to preserve duplicate records and search a stable snapshot. If your immediate problem is arranging records in the first place, start with Python sorting. Here, ordering is preparation for repeated queries, and the interesting work begins at the boundaries.

Write the query contract before choosing a boundary

Our record has two fields: an integer key and a string label. Labels distinguish records that share a key; they do not participate in sorting. A snapshot accepts an iterable of records, validates it, sorts by key, and retains the input order among equal keys. Its public records and keys are tuples. A caller can inspect them, but ordinary list operations cannot append a record to the snapshot or reorder its keys.

The public interface deliberately exposes four questions. The equal method returns every record whose key equals the probe. The range method returns records whose keys are at least the lower endpoint and strictly below the upper endpoint. Both return tuples, including an empty tuple when nothing qualifies. The floor method returns one record at the greatest qualifying key at or below the probe. The ceiling method returns one record at the least qualifying key at or above the probe. A missing neighbor is represented by None.

Duplicates make the last two statements incomplete. At an exact floor match, this example chooses the last record in input order within the matching key group. At an exact ceiling match, it chooses the first. The same tie policy applies when the qualifying key is below or above the probe. These choices follow naturally from the boundaries we will use, but they still belong in the application contract. A timestamp alone may be insufficient if your actual requirement is a particular source, revision, or event identifier.

Reversed ranges raise ValueError. Equal endpoints produce an empty range. Keys and query endpoints must have the exact built-in integer type; booleans and integer subclasses are rejected. The constructor also has a maximum record count, defaulting to 100,000. That is a limit for this teaching implementation, not a workload recommendation. These decisions reduce the number of interpretations the implementation must support and make incorrect input fail close to its source.

Read bisect results as gaps between records

For a sequence of five elements, there are six possible insertion positions, including the gap before the first element and the gap after the last. A returned position therefore need not identify an existing record. The rightmost valid insertion position is the sequence length, which would be outside the valid element indexes. Keeping positions and records conceptually separate prevents both missing-value mistakes and accidental out-of-bounds indexing.

Python provides two boundary searches. The left search places the boundary before an equal-key group; the right search places it after that group. The library compares ordering rather than asking whether it has found an equal object. With our keys, a probe of 20 has left boundary 1 and right boundary 4. Positions 1 through 3 form the matching group. The number of matches is therefore the difference between the boundaries, which is three.

A probe of 25 is just as important. Both boundaries are 4, even though no key equals 25. That position is where 25 could be placed while preserving order. Returning the record at position 4 would return key 35 and mislabel an insertion position as an exact result. An exact single-record lookup must check that the position is inside the sequence and that its key equals the probe. Our equal method instead slices between the two boundaries; an absent probe gives an empty slice.

The empty case follows the same model without a special search algorithm. Both boundaries of an empty sequence are zero. The matching slice is empty, and neither neighbor exists. A probe larger than every stored key returns the sequence length for both boundaries. A probe smaller than every stored key returns zero. Treating these as ordinary positions makes the edge cases easier to derive than treating them as failed searches with exceptional meaning.

Sorted keys 10, 20, 20, 20, 35 have left boundary 1 and right boundary 4 for probe 20; slice 1:4 contains three matches.
For probe 20, the equal-key slice starts at bisect_left and stops before bisect_right.

When debugging, write the keys on one line and number the gaps on another. Mark the returned boundary before selecting a record. This small exercise catches a common mental shortcut: reading a boundary of four as “the fourth match” instead of “four elements occur before this cut.” It also makes clear why a right boundary usually requires subtracting one for a floor lookup, while a left boundary can directly identify a ceiling candidate.

Build one snapshot with aligned records and keys

The implementation stores parallel tuples: sorted records for returned values and sorted integer keys for searching. Position i in the key tuple describes position i in the record tuple. This alignment is the snapshot’s main invariant. Construct both tuples from the same sorted record sequence. Sorting the keys independently and leaving records in their original order would produce convincing boundary numbers paired with unrelated labels.

Keeping a separate key tuple makes the query path straightforward. The probe is already an integer, and no record extraction function runs during a search. This costs another tuple of references, so it is a tradeoff rather than an automatic improvement for every workload. For a small number of queries, using bisect with a key function may be perfectly reasonable. In that API, the probe must already be in the key’s comparison domain; the search does not transform it with the key function.

Input order matters within a duplicate group. Imagine three records arriving in this order: key 20 labeled “north,” key 20 labeled “south,” and key 20 labeled “west.” A stable key-only sort preserves that sequence. Sorting by a tuple containing both key and label would silently replace the tie contract with alphabetical order. Converting records to a set would lose duplicates or ordering information that the query interface promises to preserve.

The snapshot also separates construction from use. Appending to the original input list after construction should not change an existing index. To reflect new data, build a new snapshot and choose explicitly when consumers begin using it. This suits a batch that is loaded once and queried repeatedly. It is a poor fit for an application that must insert or remove individual records continuously with low update latency.

Frozen dataclasses prevent ordinary field reassignment, and tuples prevent ordinary sequence mutation. They do not create a security boundary or freeze arbitrary nested objects. This record keeps its fields to integers and strings, avoiding an embedded mutable payload. If you later add a list of annotations, a frozen record can still contain a list that changes. Review that extension as an ownership decision; the related dataclasses guide covers that broader concern.

Derive a half-open range from two lower boundaries

A half-open range includes its lower endpoint and excludes its upper endpoint. For the query from 20 up to 35, every 20 qualifies and the 35 does not. Find the left boundary of 20 to identify the first eligible position. Then find the left boundary of 35 to identify the first position that must be excluded. Slicing the records between those cuts gives the complete answer without inspecting every key individually.

Both calls use the left variant for a reason. The lower cut must sit before all records equal to the lower endpoint so that none are skipped. The upper cut must sit before all records equal to the upper endpoint so that none are included. Changing the upper call to the right variant changes the query’s meaning: it includes every exact upper-endpoint match. That error can be invisible when test data contain no record at the upper endpoint.

Half-open windows are useful when adjacent queries should divide a snapshot cleanly. The window from 10 up to 20 contains only the 10 in our example. The next window from 20 up to 35 contains all three 20 records. A boundary record belongs to exactly one of the adjacent windows. There is no need to invent an integer “epsilon” or subtract one from an endpoint. The same cut can finish one window and begin the next.

An equal-endpoint query has identical cuts and returns an empty tuple. That is a meaningful empty window, even when records exist at that key. A reversed query is different: accepting it as an empty slice could conceal a swapped argument or a mistaken unit conversion. Raising ValueError gives the caller a chance to fix the request rather than interpreting invalid bounds as evidence that the dataset contains nothing.

This operation filters point keys. It does not discover overlaps between intervals, merge touching reservations, or determine whether one duration contains another. Those problems require a different data model, explored in Python interval logic. Reusing half-open notation is helpful, but it does not make a single-key index an interval index. Keep the meaning of each stored record explicit when applying this example to real data.

Choose floor and ceiling records deliberately

For floor, move to the right boundary of the probe and select the preceding record. Everything before that cut has a key no greater than the probe. The preceding record is therefore the last available qualifying candidate. When the cut is zero, there is no preceding record, and the answer is None. Checking that condition before subtracting matters because Python accepts negative indexes.

For ceiling, use the left boundary and select the record at that position. If the boundary equals the number of records, no qualifying candidate remains. Otherwise, that position holds the first key at or above the probe. The two methods are symmetric at the level of inequalities, although one selects before its cut and the other selects at its cut.

With the three labeled 20 records, floor at 20 selects “west,” while ceiling at 20 selects “north.” At 25, floor still selects “west,” but ceiling selects the record at 35. Thus an exact probe can produce two different records with the same key. That is intentional. Tests that compare only returned keys would miss a broken duplicate tie policy, so compare full records or their labels as well.

Records A 10, B 20, C 20, D 20, E 35: range 20 to 35 includes B, C, D. Floor 20 is D; ceiling 20 is B. Floor 25 is D; ceiling 25 is E.
The index uses half-open ranges and deliberately different tie choices for floor and ceiling.

Floor does not mean “closest,” and ceiling does not mean “next strictly greater.” A nearest-neighbor query would need to compare distances and define how equal distances are resolved. A strictly greater query would start at the right boundary instead. Name those operations separately if they become requirements. Trying to make a single “find” function choose among these meanings based on circumstance makes it difficult for callers to predict which record they will receive.

Validate the comparison domain and construction limit

The narrow integer contract is intentional. Python booleans behave as an integer subtype, which can let True pass a conventional instance check for integers. In a sequence-number index, silently interpreting a boolean as key one is more likely to conceal a caller mistake than provide useful flexibility. The lab checks exact types so that record construction and every query reject the same ambiguous input.

Rejecting integer subclasses also avoids accepting custom comparison behavior under an apparently simple integer interface. This is stricter than many general-purpose Python APIs, and that strictness should be visible to callers. If an application must accept external numeric types, normalize them at an explicit input boundary with documented conversion rules. Do not quietly truncate fractional values or turn textual identifiers into numbers inside the search method.

A similar decision applies to floating-point data. Supporting floats would require a policy for non-finite values and the relationship between equality and ordering. Approximating equality with a tolerance introduces another question: is the desired answer a single representative or every record in a numeric window? The current implementation sidesteps those questions by accepting only integers. Extending the annotation without changing validation, documentation, and tests would not be a complete extension.

The record cap limits how many inputs the constructor will retain and sort. A bounded collection loop should detect one item beyond the configured limit and reject the input instead of materializing an unbounded iterable first. This makes an endless but promptly yielding generator fail after a bounded number of yields. It does not impose a timeout on a generator that blocks before yielding its next item.

A record-count cap is also not a byte budget. Labels can be long, integer values can be large, and the source iterable can perform expensive work of its own. In an application exposed to untrusted input, enforce limits before this layer: decoded message sizes, permitted label length, execution deadlines, and any required numeric range. This lab provides a focused search contract, not an ingestion sandbox.

Keep key bounds separate from positional bounds

The library also accepts optional lo and hi arguments that restrict which positions it searches. Those are array offsets, whereas this article’s range endpoints are key values. On a five-record snapshot, a high key of 35 can be meaningful, but a positional upper limit of 35 does not describe the same request. Passing application range endpoints directly into those positional arguments confuses two different coordinate systems.

The wrapper avoids that ambiguity by searching the full key tuple for each endpoint. If you later expose positional subranges, document whether returned positions refer to the original snapshot and whether a duplicate group may be cut in half by the restricted region. Test probes exactly at both positional edges. A limited search window can be useful, but it changes which records are eligible before the boundary algorithm even starts.

Follow the implementation from construction to query

Download the original tested Python bisect lab, including implementation, demo, tests and verification notes. Standard library only; no model account or API key is needed.

The complete implementation below keeps construction and queries in one small module. Read the constructor first. Its job is to validate records, enforce the count limit, obtain stable key order, and install the two aligned tuples. Search methods can then rely on those established conditions instead of repeating sorting or scanning validation on every call. Revalidating the entire snapshot during each query would erase much of the reason to build an index.

"""A read-only, integer-keyed snapshot for learning bisect boundaries.

Python 3.10+. Standard library only. No insertion or update operations.
"""
from bisect import bisect_left, bisect_right
from dataclasses import dataclass
from typing import Iterable


def _require_int(value: object, name: str) -> None:
    if type(value) is not int:
        raise TypeError(f"{name} must be an exact int")


@dataclass(frozen=True, slots=True)
class Record:
    key: int
    label: str

    def __post_init__(self) -> None:
        _require_int(self.key, "key")
        if type(self.label) is not str:
            raise TypeError("label must be an exact str")


@dataclass(frozen=True, slots=True, init=False)
class SortedIndex:
    records: tuple[Record, ...]
    keys: tuple[int, ...]

    def __init__(
        self, records: Iterable[Record], *, max_records: int = 100_000
    ) -> None:
        _require_int(max_records, "max_records")
        if max_records < 0:
            raise ValueError("max_records must be nonnegative")
        collected = []
        for record in records:
            if len(collected) == max_records:
                raise ValueError("record count exceeds max_records")
            if type(record) is not Record:
                raise TypeError("every item must be an exact Record")
            collected.append(record)
        # Python's stable sort preserves source order among duplicate keys.
        collected.sort(key=lambda record: record.key)
        snapshot = tuple(collected)
        object.__setattr__(self, "records", snapshot)
        object.__setattr__(self, "keys", tuple(record.key for record in snapshot))

    def equal(self, key: int) -> tuple[Record, ...]:
        """Return all equal-key records in their original input order."""
        _require_int(key, "key")
        left = bisect_left(self.keys, key)
        right = bisect_right(self.keys, key)
        return self.records[left:right]

    def range(self, low: int, high: int) -> tuple[Record, ...]:
        """Return records with low <= key < high, sorted by key."""
        _require_int(low, "low")
        _require_int(high, "high")
        if low > high:
            raise ValueError("low must not exceed high")
        left = bisect_left(self.keys, low)
        right = bisect_left(self.keys, high)
        return self.records[left:right]

    def floor(self, key: int) -> Record | None:
        """Greatest key <= key; last input-order tie; None if absent."""
        _require_int(key, "key")
        position = bisect_right(self.keys, key)
        return self.records[position - 1] if position else None

    def ceiling(self, key: int) -> Record | None:
        """Smallest key >= key; first input-order tie; None if absent."""
        _require_int(key, "key")
        position = bisect_left(self.keys, key)
        return self.records[position] if position < len(self.records) else None

Next, read the query methods as translations of the earlier contracts. Equal takes the slice between left and right boundaries. Range takes the slice between two left boundaries after validating endpoint order. Floor checks the right boundary before stepping back. Ceiling checks the left boundary before indexing. The small number of operations is helpful during review: each conditional should correspond to a named invalid-input or missing-result case.

"""Run: python demo.py"""
from bisect import bisect_left, bisect_right
from bisect_index import Record, SortedIndex


def labels(records):
    return [record.label for record in records]


def main():
    index = SortedIndex([
        Record(20, "B"), Record(10, "A"),
        Record(20, "C"), Record(35, "E"), Record(20, "D"),
    ])
    print("keys:", index.keys)
    print("20 boundaries:", bisect_left(index.keys, 20), bisect_right(index.keys, 20))
    print("equal(20):", labels(index.equal(20)))
    print("equal(25):", labels(index.equal(25)))
    print("range(20, 35):", labels(index.range(20, 35)))
    for probe in (20, 25):
        print(f"floor({probe}):", index.floor(probe))
        print(f"ceiling({probe}):", index.ceiling(probe))
    print("floor(9):", index.floor(9))
    print("ceiling(36):", index.ceiling(36))


if __name__ == "__main__":
    main()

Executed demonstration output:

keys: (10, 20, 20, 20, 35)
20 boundaries: 1 4
equal(20): ['B', 'C', 'D']
equal(25): []
range(20, 35): ['B', 'C', 'D']
floor(20): Record(key=20, label='D')
ceiling(20): Record(key=20, label='B')
floor(25): Record(key=20, label='D')
ceiling(25): Record(key=35, label='E')
floor(9): None
ceiling(36): None

Run the demonstration before modifying the example. Its labels make duplicate order observable, and its probes should cover an exact duplicate key, a missing interior key, and the ends of the snapshot. Then change the input order of the three equal-key records and predict how floor and ceiling change. This is a useful manual check that the implementation preserves the stated tie policy rather than accidentally relying on label order.

Use counterexamples that expose the wrong question

The most productive review examples are small enough to understand without running code. Start with a missing interior key: searching for 25 in our snapshot must not report 35 as an exact match. Next, ask for floor below 10. An implementation that indexes the right boundary minus one without checking zero will return the last record through negative indexing. Both defects can survive a large happy-path example.

To expose an inclusive upper endpoint, ask for the range from 20 up to 35 and retain a record at 35. To expose a skipped lower duplicate, retain several 20 records rather than a single one. To expose a changed tie policy, use labels deliberately out of alphabetical order. The test data should make incorrect alternatives produce visibly different results.

Another failure comes from sorting only once while leaving a mutable backing list available to callers. A caller can append a smaller key or alter a record after the index is built, and a later boundary search then operates on a sequence whose assumptions no longer hold. Snapshot construction removes normal list-level aliasing from this example. It does not justify ignoring mutation if the design later changes to store user-defined mutable records.

Finally, do not infer deterministic business meaning from stable input order alone. A stable sort preserves the order it receives; it cannot repair an upstream feed whose duplicate records arrive in an arbitrary order. If “latest revision” matters, include a revision or sequence rule in the contract and normalize the input accordingly. Otherwise, two independently built snapshots can follow the same algorithm yet select different duplicate records because their source orders differ.

Test against an independent linear answer

A test that repeats the same pair of bisect calls as the implementation can reproduce the same mistake. For small fixtures, build the expected result with a direct predicate over stably sorted records. Exact results retain records whose keys equal the probe. Range results retain records satisfying the lower-inclusive, upper-exclusive condition. These slower calculations are easy to inspect and provide an independent path to the expected answer.

Neighbor oracles can also stay simple. Collect the records whose keys are no greater than the probe and select the last, or return None if the collection is empty. For ceiling, collect records whose keys are no smaller and select the first. Because the reference sequence preserves duplicate input order, these checks verify both key selection and tie selection.

Use short exhaustive inputs to exercise combinations that individual examples miss. A small key alphabet naturally produces duplicates, and permutations vary their placement before sorting. Probe below the alphabet, at its values, between them where possible, and above it. Include empty input and one-record input. Exhaustive checks over a declared finite domain provide concrete evidence for that domain; they do not establish correctness for every possible object or application.

Executed result: all 14 unittest methods passed on CPython 3.12.14 and 3.13.5, normally and with -O. Author tests include 364 exhaustive short sequences. Independent review adds 781 exhaustive sequences and 100 seeded larger cases, with linear original-input oracles and validation checks. These are finite-domain results, not a universal proof or performance benchmark.

Validation deserves separate tests. Check boolean probes, non-integer endpoints, reversed bounds, invalid record fields, and the constructor limit. Confirm that a generator at the limit is accepted and one beyond it is rejected under the documented behavior. Check that changing the original container after construction leaves the snapshot unchanged. These cases test the protective parts of the interface rather than only the arithmetic of boundary selection.

The property-based testing guide offers a useful next step when inputs become more varied. For this lab, deterministic reference comparisons keep the evidence reproducible with the standard library. Record the interpreter, command, number of tests, and any finite-domain counts separately. A passing test summary should make clear what was exercised without turning a test count into a claim about production reliability.

Give DeepSeek a contract and ask for counterexamples

A focused review request gives a model something concrete to challenge. Supply the interface, duplicate policy, endpoint rules, and implementation together. Ask it to trace specific probes before proposing changes. Without that context, a reviewer could reasonably suggest removing duplicates or choosing a different tie, improving the code against a requirement you never intended.

The following prompts are templates for a review you can run yourself. They have not been executed for this article, and no response quality or model capability is inferred from them. Use synthetic records when sharing examples. A realistic-looking customer label or private event payload adds nothing to a boundary review and may expose information unnecessarily.

Unexecuted review prompt:
Review this SortedIndex implementation against this exact contract:
keys are exact built-in integers; duplicates preserve input order;
equal returns all matches; range is [low, high); reversed bounds raise;
floor selects the last tie; ceiling selects the first tie;
missing neighbors return None. Do not change the contract.
Trace keys [10, 20, 20, 20, 35] for probes 5, 20, 25, and 40.
Give the smallest counterexample for each defect you identify.
Separate confirmed defects from optional design changes.
[Paste the implementation and tests.]

A second pass can inspect the tests rather than the implementation. Ask which incorrect variants would still pass: using the wrong upper boundary, omitting the floor guard, sorting ties by label, or returning one duplicate instead of all matches. This turns the review toward observable weaknesses in the evidence. Verify any proposed counterexample locally and add it only if it expresses the contract you actually want.

Unexecuted test-review prompt:
Read the contract and tests below. Identify any contract clause without
an independent expected-result check. For each gap, propose one small
fixture and its exact expected records. Do not claim to run the code.
Explain whether the fixture distinguishes the correct implementation
from a plausible one-line boundary error.
[Paste the contract and tests.]

Account for result size and snapshot rebuilds

A boundary search examines only a logarithmic number of positions under the usual constant-cost comparison model. That does not make every method’s total work logarithmic. Returning a tuple slice of many records requires producing the result. Equal and range therefore have a result-size component in addition to finding their cuts. A query that returns nearly the entire snapshot still has nearly the entire snapshot to deliver.

The constructor pays for validation, sorting, and building both tuples. That up-front work makes sense when the same snapshot serves enough queries to justify it. For a one-off filter over a small collection, a direct comprehension may be clearer and sufficiently fast. Measure the operation your application performs, including construction and result consumption, rather than timing only the bisect call and presenting it as end-to-end performance.

Updates also change the calculation. Rebuilding a snapshot for every incoming record repeatedly pays the construction cost. A workload with frequent writes may need a different structure or storage system. Conversely, a periodic batch followed by many read queries can make snapshot replacement an understandable design. The correct choice depends on update frequency, data size, output size, and operational constraints that this tutorial does not benchmark.

Python’s bisect documentation warns against assuming thread safety for concurrent use of the same sequence. This example does not supply a concurrency protocol or demonstrate thread-safe publication. Its immutable-facing interface narrows ordinary mutation paths, but a shared service still needs an explicit coordination design appropriate to its runtime. Do not turn the absence of an insert method into a blanket concurrency guarantee.

Frequently asked questions

Why not use a dictionary for exact queries?

If exact-key lookup is the entire requirement, a dictionary mapping each key to its records may be a better fit. The sorted snapshot earns its place when ordered questions also matter: windows, floor, and ceiling. Maintaining both structures can serve mixed workloads, but then construction and consistency become additional responsibilities. Start with the questions callers need rather than choosing an index because its search operation sounds fast.

Does an empty result mean the input was invalid?

No. A valid probe can have no exact matches, and a valid window can contain no records. The interface separates those outcomes from invalid types or reversed bounds by returning an empty tuple for valid empty collections and raising for invalid requests. Missing neighbors use None because those methods return at most one record. Callers should preserve that distinction when translating results into application responses.

Can I sort descending and keep the same methods?

The boundary derivations here assume ascending keys. Reversing the records without changing the search strategy breaks that premise. If a display needs newest-first results, one option is to search the ascending snapshot and reverse the returned records for presentation. Check whether duplicate display order should reverse too. A descending index needs its own documented comparison and boundary rules rather than a reversed construction line alone.

How should I adapt this to time values?

Choose one explicit time representation and unit before adapting the example. Integer ticks can fit this interface, but timestamps from different units will still be integers and can silently produce meaningless ranges. Time-zone conversion, daylight-saving ambiguities, and parsing belong at a separate input boundary. The index should receive already normalized keys whose meaning is documented, and tests should include values at the exact start and end of a window.

What should change before production use?

Evaluate input limits, snapshot refresh behavior, observability, memory use, and the actual access pattern. Decide how errors reach callers and whether returning full slices is acceptable for large results. Add application-specific tests and measurements. The lab establishes a small, inspectable contract with reproducible checks; it does not include persistence, pagination, authorization, distributed updates, or service-level performance evidence.

Make the boundary contract visible

The useful result is a set of named questions whose answers remain predictable when duplicates and missing values appear. Preserve the relationship between records and keys, mark the cuts before selecting records, and test the smallest cases that distinguish neighboring interpretations. A DeepSeek review can be organized around those same concrete obligations, while execution and expected results remain independently checkable in your own Python environment.

Sources & References

Official Python references consulted on October 8 and rechecked on October 11, 2026. The example design, labeled fixtures, review prompts, and application tradeoffs are original to this tutorial.

Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *