all Python 3bisectterm
bisect
module
Binary search and insertion into a sorted list without re-sorting it.
Syntax
import bisect
Use it when a list is already sorted and you need a position fast: the search is O(log n). Insertion with insort keeps the order but still shifts elements in O(n); for frequent inserts and min-extraction heapq fits better. The module does not check that the list is sorted — on an unsorted one it silently gives a wrong answer.
Examples
import bisect
scores = [10, 20, 30, 40]
print(bisect.bisect_left(scores, 25)) # → 2
bisect.insort(scores, 25)
print(scores) # → [10, 20, 25, 30, 40]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy