Code Snippets
/

bisect for Sorted-List Insertion

bisect for Sorted-List Insertion

The `bisect` module is Python's binary-search-on-a-list primitive: `bisect_left` and `bisect_right` find the insertion index for a value in a sorted list in O(log n). This snippet covers the basic insertion-point query, the `insort` shortcut for keeping a list sorted as you build it, and the count-occurrences and rank-percentile recipes that fall out for free.

Python
Medium
3 snippets
py-standard-library
binary-search
code-template
algorithms

189 views

2

import bisect

sorted_nums = [1, 3, 4, 4, 4, 6, 9]

print(bisect.bisect_left(sorted_nums, 4))   # 2 (first index where 4 belongs)
print(bisect.bisect_right(sorted_nums, 4))  # 5 (one past the last 4)
print(bisect.bisect_left(sorted_nums, 5))   # 5 (would insert before 6)
print(bisect.bisect_left(sorted_nums, 0))   # 0 (insert at start)
print(bisect.bisect_left(sorted_nums, 99))  # 7 (insert at end)

bisect_left(a, x) returns the leftmost index where x can be inserted to keep a sorted; bisect_right(a, x) returns one past the rightmost equal value. Both run in O(log n). The two together let you locate every occurrence of a value: bisect_right(a, x) - bisect_left(a, x) is the count. Note that bisect does NOT verify the list is sorted; passing an unsorted list silently returns garbage, which is a class of bug worth knowing about.