HOWTO · Python

Python Bisect - Binary Search

Learn how Python’s bisect module finds insertion points, searches sorted lists, and inserts values while preserving order.

On this page
Note
For background on the binary-search algorithm, see the binary search algorithm article.

Python’s bisect module finds insertion points in an already sorted sequence. It does not sort the sequence or search for roots of functions. Its bisect_left() and bisect_right() functions locate the two sides of a value’s equal range; insort() uses those positions to insert while preserving order.

bisect Module and the Sorted-List Requirement

Import the functions from the standard-library module with from bisect import bisect_left, bisect_right, insort. The sequence must already be sorted in the same order used by the comparisons. If it is out of order, an insertion point does not make it sorted, and searches can give misleading results.

The functions return an index between the selected bounds, including the right endpoint. You can restrict a search to a slice of the list with lo and hi; the default search range is from index 0 up to len(values). The list itself is not copied or changed by a bisect search.

bisect_left() and bisect_right() Insertion Points

For a sorted list values and target x, bisect_left(values, x) returns the first index whose value is greater than or equal to x. Everything before that index is less than x; everything from it onward is greater than or equal to x.

bisect_right(values, x) returns the first index whose value is greater than x. Everything before it is less than or equal to x; everything from it onward is greater than x. When duplicates are present, the two results mark the start and end of their range. If x is absent, both insertion points are equal. A result of 0 means the insertion point is at the beginning; a result equal to the list length means it is at the end.

Search for Values with bisect

A bisect call returns an insertion index, not a confirmation that the target exists. To find the first matching item, check that the left index is in range and that the item at that index equals the target. To find the last matching item, use the right index minus one, then check that this index is nonnegative and matches. These checks handle absent values and insertion points at either end.

Run this example:

from bisect import bisect_left, bisect_right

values = [1, 2, 4, 4, 4, 8]
target = 4

first = bisect_left(values, target)
last = bisect_right(values, target) - 1
first_match = first if first < len(values) and values[first] == target else None
last_match = last if last >= 0 and values[last] == target else None

below = bisect_left(values, 7) - 1
below_value = values[below] if below >= 0 else None

print(first_match, last_match, below_value)
2 4 4

For the values shown, the selected indices are 2 and 4, and the greatest value below 7 is 4. The output shows the first matching index, last matching index, and greatest value below 7, in that order.

The same checks work for other targets: None indicates there is no matching item or no value below the target. For the greatest value strictly below x, subtract one from bisect_left(values, x) and check that the resulting index is at least zero before indexing. This is important when the insertion point is at the start of the list. To search only part of a list, pass matching lo and hi bounds to the bisect call; then make sure any subsequent indexing or match check uses that same range.

Insert Values with insort

Use insort(values, x) to insert x into its sorted position. By default it inserts to the right of existing equal values. insort_left(values, x) inserts before equal values, while insort_right(values, x) is equivalent to the default behavior. These functions modify the list in place, so retain a reference to the list you pass in.

The ordering requirement still applies: start with a sorted list, and use comparisons consistent with its existing order. If you need to insert only within a range, compute an insertion point with bisect_left() or bisect_right() and call values.insert(index, x); ensure the chosen bounds and insertion location match the portion of the list you intend to maintain.

Performance and Limitations

Finding an insertion point takes logarithmic time because each comparison halves the remaining search range. Inserting into a Python list can take linear time because later elements may need to move to make room. Therefore, repeated insort() calls on a large list may be slower than using a data structure designed for frequent ordered insertions.

bisect relies on ordering comparisons; it does not use equality to locate an insertion point. For custom objects, define a consistent ordering and, where appropriate, pass a key function to the bisect functions. The key is applied to list elements during the search, while the value being inserted or searched is supplied as x; prepare x in the corresponding comparison form when using a key. Keep the list sorted according to that same key as it changes.