Where Does This Value Belong? Binary Search with Python's bisect

This article explains how the bisect module finds positions in sorted lists by binary search, how left and right positions give counts, ranks and brackets, how the key parameter works, and why insort remains linear.

A yellow-green tree python coiled over a branch, its head resting exactly at the centre of its loops against a dark background
Photo by Alexander Ross on Unsplash

Many programs keep data in sorted order, such as timestamps, prices, scores or thresholds, and repeatedly ask where a value belongs among them. A linear scan answers the question by examining the elements one by one, so its cost grows with the length of the list. The present article examines the bisect module of the standard library, which answers it by binary search, halving the candidate range at each step. It explains the difference between the left and right positions, uses them for membership tests, counts and ranges, applies the key parameter introduced in Python 3.10, and measures both the speed of the search and the cost of insertion, which the module does not make logarithmic. Finding the place of a value among a million sorted values in about twenty comparisons is the secret weapon of bisect.

Finding Positions with bisect_left and bisect_right

The two basic functions return the index at which a value would be inserted to keep the list sorted, and they differ only when the value is already present: bisect_left returns the position before the existing equal elements, and bisect_right, also available as bisect, returns the position after them. The left position also gives an efficient membership test, because an equal element, if any, must be at that index.

import bisect

scores = [10, 20, 20, 20, 30]
print(bisect.bisect_left(scores, 20), bisect.bisect_right(scores, 20))  # Output: 1 4
print(bisect.bisect_right(scores, 20) - bisect.bisect_left(scores, 20))  # Output: 3

def contains(seq, x):
    i = bisect.bisect_left(seq, x)
    return i < len(seq) and seq[i] == x

print(contains(scores, 25), contains(scores, 30))  # Output: False True

The difference between the two positions is the number of occurrences of the value, computed without visiting them. The membership function examines one element after the search, so it runs in logarithmic time, whereas x in scores scans the list from the beginning.

Ranks, Ranges and Brackets

Competitive games publish leaderboards in which a player's rank among millions of sorted ratings appears immediately after a match, and the same question, how many values lie below or above a given one, is exactly what the two positions answer. This means that the rank of a value, the number of elements in a closed interval and the bracket into which a value falls are all differences or lookups based on bisect_left and bisect_right. The analogy, however, stops at this point, because a leaderboard is updated continuously by a server designed for that purpose, whereas inserting into a Python list costs time proportional to its length, as the pitfalls below show. The following example counts the values within an interval and maps scores to grades, the example that the documentation of the module itself uses.

import bisect

def count_between(seq, low, high):
    return bisect.bisect_right(seq, high) - bisect.bisect_left(seq, low)

ages = [18, 21, 25, 25, 30, 42, 57]
print(count_between(ages, 21, 30))  # Output: 4

def grade(score, breakpoints=(60, 70, 80, 90), grades="FDCBA"):
    return grades[bisect.bisect(breakpoints, score)]

print([grade(s) for s in (33, 60, 85, 90, 100)])  # Output: ['F', 'D', 'B', 'A', 'A']

The interval count uses the left position for the lower bound and the right position for the upper bound, so both limits are included. In the grade function, a score equal to a breakpoint belongs to the higher grade, because bisect places it after the equal value; replacing it with bisect_left would move every boundary score down one grade.

Searching Records with key

Since Python 3.10, every function of the module accepts a key argument, which extracts the comparison value from each element of the list, so lists of records can be searched without a parallel list of keys. The key has an asymmetry that surprises many readers: the search functions apply it to the elements but not to the value being searched for, which must already be a key, while the insertion functions apply it to the new element as well.

import bisect
from operator import itemgetter

rows = [("ada", 30), ("bob", 45), ("eve", 60)]
print(bisect.bisect_left(rows, 45, key=itemgetter(1)))  # Output: 1
bisect.insort(rows, ("cy", 50), key=itemgetter(1))
print(rows)  # Output: [('ada', 30), ('bob', 45), ('cy', 50), ('eve', 60)]
try:
    bisect.bisect_left(rows, ("x", 50), key=itemgetter(1))
except TypeError as error:
    print(error)  # Output: '<' not supported between instances of 'int' and 'tuple'

The search for 45 receives the number, not a record, and the insertion receives a complete record whose key is extracted automatically; passing a record to the search fails because the key is not applied to it. Records that define their own ordering, such as data classes declared with order=True and described in the article devoted to data classes, can be searched without any key, provided the field that matters comes first. When the key function is expensive, the documentation suggests caching it or searching a precomputed list of keys.

Pitfalls of the bisect Module

Binary search is only correct on sorted data and only fast for searching, so most errors with bisect come from forgetting one of those two conditions. Six pitfalls are distinguished, which are the following:

  1. Unsorted input. The module never checks the order of the list, so on unsorted data it returns a position without meaning, and no error is raised.
  2. Insertion is linear. insort finds the position in logarithmic time but then shifts every later element, so building a large list by repeated insort is quadratic.
  3. The key asymmetry. Search functions expect a key value, insertion functions expect a full element.
  4. Left versus right at boundaries. Choosing the wrong function moves every value that equals a breakpoint to the neighbouring bracket.
  5. Inconsistent ordering. Elements whose comparison is not a total order, such as floats that include nan, make the result unpredictable.
  6. A sorted list where a set suffices. Pure membership tests are faster with a set, which needs no order at all.

The following example measures the search against a linear scan and reproduces the first pitfall.

import bisect
import timeit

data = list(range(1_000_000))
search = timeit.timeit(lambda: bisect.bisect_left(data, 987_654), number=20)
scan = timeit.timeit(lambda: data.index(987_654), number=20)
print(scan > 100 * search)            # Output: True
print(bisect.bisect_left([3, 1, 2], 2))  # Output: 2

On CPython 3.12, each call to index took about 4 milliseconds, while each binary search took about 0.4 microseconds, a difference of four orders of magnitude; inserting into the same list with insort took about 0.25 milliseconds per call, almost all of it spent shifting elements. The last line returns index 2 for a list that is not sorted, a position that means nothing. When many insertions and removals must keep data sorted, a structure designed for it, such as the third-party sortedcontainers package, or a different design, such as appending to a deque described in the article devoted to deque and sorting once, is preferable.

Choosing a Search Strategy

Consequently, bisect fits sorted data that is searched often and modified rarely, as the following table summarizes.

Situation Recommended approach
Membership only, no order needed A set
Lookup by exact key A dict
Many searches on sorted data, few insertions bisect_left and bisect_right
Counting values in a range or computing a rank Differences of bisect_right and bisect_left
Mapping numbers to brackets bisect over a tuple of breakpoints
Frequent insertions while staying sorted A sorted container library, or collect and sort once
Repeatedly taking the smallest element A heap, through heapq

Conclusion

It is concluded that the bisect module finds positions in sorted lists by binary search, which makes membership tests, counts, ranks and bracket lookups logarithmic, and that since Python 3.10 it searches records through a key whose application differs between searching and inserting. This magic applies to searching only: insertion remains linear, and the module trusts the caller to keep the list sorted. Controlling how an object is created, before its initializer receives it, is the purpose of the special method __new__, which is developed in a future article of this series.