Batu Lab NotesPractical developer guides

Separate bisect insertion position from exact membership

By Batu ยท English technical notes

Separate bisect insertion position from exact membership

Direct answer: bisect_left() returns where a value belongs in sorted order; it does not establish that the value is present. After calling it, check both index < len(values) and values[index] == target before reporting a match.

The experiment uses [1, 4, 7]. Target 4 is present and returns insertion index 1. Target 5 is absent but returns 2, the position immediately before 7. Treating any returned index as a match incorrectly labels both lookups as successful. The helper keeps the two facts separate: insertion_index describes the ordered boundary, while found describes exact membership.

This distinction follows the contract for bisect_left(): it locates an insertion point and relies on less-than comparisons rather than equality to decide whether it found an item. It also works only when the searched sequence is already sorted according to the comparison being used. The assertions verify these two fixture results; they do not prove that an arbitrary list is sorted or that concurrent mutation is safe.

bisect_left() is available in all supported Python 3 versions. Its optional key parameter requires Python 3.10+.

AI-assistance disclosure: Batu Lab Notes used AI assistance to draft this synthetic example and explanation.

Example

from bisect import bisect_left


def lookup_sorted(values, target):
    index = bisect_left(values, target)
    found = index < len(values) and values[index] == target
    return {"insertion_index": index, "found": found}


values = [1, 4, 7]
for target, expected in ((4, (1, True)), (5, (2, False))):
    result = lookup_sorted(values, target)
    observed = (result["insertion_index"], result["found"])
    assert observed == expected
    print(f"{target}: {observed}")

Expected output:

4: (1, True)
5: (2, False)