Incremental ordered insertion
Maintain a sorted in-memory collection as records arrive.
Python · Module
The bisect module finds insertion points in sorted sequences and provides helpers for inserting values without resorting the list. Left and right variants control whether duplicates are placed before or after existing equal values.
The module locates insertion points in an already sorted sequence using comparisons, then optionally inserts through list operations. Left variants place an equal value before existing equals; right variants place it after them. Bounds can restrict the search to a slice, and key functions can define the ordering for supported APIs.
bisect_left(a, x, lo=0, hi=len(a), *, key=None)
bisect_right(a, x, lo=0, hi=len(a), *, key=None)
bisect(a, x, lo=0, hi=len(a), *, key=None)
insort_left(a, x, lo=0, hi=len(a), *, key=None)
insort_right(a, x, lo=0, hi=len(a), *, key=None)
insort(a, x, lo=0, hi=len(a), *, key=None)| Name | Type | Description |
|---|---|---|
a | sequence/list | Sorted sequence being searched or modified. |
x | value | Value whose insertion position is located or which is inserted. |
lo | int | Lower bound of the search range; defaults to 0. |
hi | int | Upper bound of the search range; defaults to len(a). |
key | callable | None | Optional ordering function for supported modern APIs. |
The bisect search functions return an integer insertion index; insort functions modify the list in place and return None.
from bisect import bisect_left, insort
scores = [10, 20, 20, 40]
position = bisect_left(scores, 20)
insort(scores, 25)
print(position, scores)Finds the first valid position for 20, then inserts 25 while preserving sorted order.
Maintain a sorted in-memory collection as records arrive.
Locate the lower or upper boundary of a value range.
Restrict searching to a known sorted section.
bisect_left returns the first position where x can be inserted while keeping the list sorted. Equal elements remain at or after that position, so it is useful for lower-bound searches.
Follow-up: How do you find whether x exists? Compute i = bisect_left(a, x), then check i < len(a) and a[i] == x.
bisect_right, also exposed as bisect, returns a position after existing entries equal to x. This makes it the upper bound of x in the sorted range.
Follow-up: How can it count equal values? Subtract bisect_left(a, x) from bisect_right(a, x).
The bisect search is logarithmic, but list insertion is linear because later elements must move. Therefore, repeated insertions can be costly for large lists.
Follow-up: What alternative fits frequent ordered insertions? The documentation points to sorted collections as an alternative; a tree-based structure can avoid array shifting.
bisect_leftbisect_rightbisectinsort_leftinsort_rightinsort