Skip to content
Python: Keep bisect keys aligned with their records

Python: Keep bisect keys aligned with their records

November 25, 2026

Repeated searches can use a precomputed key array instead of recalculating a record’s key on each comparison. The key array and record list must use the same order and receive matching insertions.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as sorted_keys_demo.py in an empty working directory:

from bisect import bisect_left, bisect_right

records = [(10, "alpha"), (30, "gamma")]
keys = [record[0] for record in records]
new_record = (20, "beta")
index = bisect_right(keys, new_record[0])
keys.insert(index, new_record[0])
records.insert(index, new_record)
assert keys == [record[0] for record in records]
print("Keys:", keys)
print("Records:", records)
for wanted in (20, 25):
    position = bisect_left(keys, wanted)
    match = records[position] if position < len(keys) and keys[position] == wanted else None
    print(f"{wanted}: {match}")

Run it without -O so any assertions remain enabled:

python3 sorted_keys_demo.py

Captured output:

Keys: [10, 20, 30]
Records: [(10, 'alpha'), (20, 'beta'), (30, 'gamma')]
20: (20, 'beta')
25: None

bisect_left() returns an insertion position even when no key matches. Check the key and bounds before using that position to retrieve a record. bisect_right() returns a position after existing equal keys, making the tie policy explicit.

Limits and cleanup

Treat the two lists as one owned data structure. Changing a record’s sort key requires rebuilding or updating the index too. The paired inserts are not an atomic transaction or a thread-safety mechanism. Searching takes logarithmic comparisons, but list insertion still shifts elements and takes linear time.

After testing, remove the example script from its working directory:

rm -- sorted_keys_demo.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on