`bisect`
bisect is the standard-library binary search on a sorted list. It finds an insertion point in O(log n) time and can keep a list ordered as you insert.
Detailed Explanation
Binary search needs a sorted sequence. bisect_left(a, x) returns the index where x should go so that every element to the left is strictly less than x. bisect_right (also named bisect) puts equal elements to the left of the insertion point. If x is present, bisect_left is the first occurrence and bisect_right is past the last.
insort_left and insort_right insert at that index. Insertion into a list is still O(n) because elements shift. The search is log n; the move is linear. insort is the right tool for a modest sorted list you query often. It is the wrong tool for high-volume inserts; use heapq if you only need the smallest, or SortedList from a third-party package if you need both.
key= on the bisect functions (3.10+) matches sorted. Older code built a parallel list of keys. The sequence must already be ordered by the same key.
Membership of a sorted list is i = bisect_left(a, x); found = i < len(a) and a[i] == x. Do not use x in a if a is long; that is a linear scan.
bisect does not sort. Passing an unsorted list produces a legal index and a wrong meaning. Sort first, or maintain the order on every insert.
Code Examples
import bisect
cutoffs = [0, 60, 70, 80, 90]
labels = ["F", "D", "C", "B", "A"]
def grade(score: int) -> str:
i = bisect.bisect_right(cutoffs, score) - 1
return labels[i]
print(grade(80), grade(59), grade(100)) # B F Askus = ["A-1", "B-2", "D-4"]
print(bisect.bisect_left(skus, "C-3")) # 2, insertion point
bisect.insort(skus, "C-3")
print(skus) # ['A-1', 'B-2', 'C-3', 'D-4']def contains(sorted_items: list[int], value: int) -> bool:
i = bisect.bisect_left(sorted_items, value)
return i < len(sorted_items) and sorted_items[i] == value
print(contains([1, 3, 5], 3), contains([1, 3, 5], 4)) # True FalseCommon Gotchas
The list must already be sorted
`bisect` will not tell you it is not. You get a quiet wrong index.
`insort` is O(n)
the binary search does not make list insertion cheap. Profile before you `insort` in a hot loop.
`bisect` vs `bisect_left`
`bisect` is `bisect_right`. Equality handling differs. Pick the one that matches the comment you would write.
`key=` needs 3.10+
on older Python, search in a precomputed key list.