Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python bisect key: search with a key value, insert with a record

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

bisect_left applies key to stored elements, while the search value is already the comparable key.

Download Python source kit

Observed contract

A due-date index stores receipt records ordered by day. The search passes day 47, rather than an entire record, to bisect_left. insort_left then receives a full new record and places it at the correct day.

Boundary

Bisection assumes the list remains sorted under the same key. Mutating a stored record's day breaks later searches. Concurrent writers also need synchronization around search and insertion; the functions do not make a shared list transactional.

Executable case

python
from bisect import bisect_left, insort_left

receipts = [
    {"due_day": 12, "receipt": "R-12"},
    {"due_day": 47, "receipt": "R-47"},
    {"due_day": 73, "receipt": "R-73"},
]
due_day = lambda receipt: receipt["due_day"]
print("found_at", bisect_left(receipts, 47, key=due_day))
insort_left(receipts, {"due_day": 26, "receipt": "R-26"}, key=due_day)
print("ordered_days", [receipt["due_day"] for receipt in receipts])

Output

Output
found_at 1
ordered_days [12, 26, 47, 73]

Cost

The search uses O(log n) comparisons, but insertion shifts list entries and costs O(n). Computing an expensive key repeatedly can dominate comparisons; keep precomputed keys when queries are frequent.

Common Mistakes

  • For bisect_left with key, pass the search key as x, not a full record.
  • Do not mutate an indexed sort field in place.
  • A log-time search does not make list insertion log-time.

Connected lessons

Test this contract.

python
bisect-key-search-contract
Storage details