bisect.bisect_left, bisect.bisect_right, bisect.bisect
bisect.bisect_left(a, x, lo=0, hi=len(a), *, key=None)
bisect.bisect_right(a, x, lo=0, hi=len(a), *, key=None)
bisect.bisect(a, x, lo=0, hi=len(a), *, key=None)Return the leftmost or rightmost insertion index for x in a sorted list.
| Parameter | Description |
|---|---|
a / x | a is a sorted sequence. x is the value to locate. When key is None, elements are compared with x directly. |
lo / hi | Optional bounds for the search. The official defaults consider the whole sequence. |
Returns: An int index in the range lo..hi inclusive, suitable as the first argument of list.insert.
- bisect.bisect is an alias of bisect_right.
- These functions do not raise if x is missing; they only return an insertion point. bisect_left on an empty list returns 0.
import bisect
a = [1, 2, 2, 2, 3]
print(bisect.bisect_left(a, 2), bisect.bisect_right(a, 2), bisect.bisect(a, 2))
print(bisect.bisect_left(a, 0), bisect.bisect_right(a, 9))
print(bisect.bisect_left([], 1))Expected output
1 4 4
0 5
0Related: heapq