Python Snippet

bisect for Sorted-List Insertion

Difficulty: Medium

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.

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

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.