Python bisect_left and bisect_right
bisect_left finds the first insertion position for a value, and bisect_right finds the position after its equals. Their difference counts matches.
A simple example
bisect_left and bisect_right
- Start with Sorted values 1, 2, 2, 3
- Do this Find left and right insertion positions for 2
- Result 1 and 3
Syntax
bisect_right(prices, target) - bisect_left(prices, target)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Count equal prices in a sorted catalog
A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.
from bisect import bisect_left, bisect_right
prices = [10, 20, 20, 40]
for target in (20, 25):
print(target, bisect_right(prices, target) - bisect_left(prices, target))
20 2 25 0
The input must remain sorted. For a missing value both boundaries are equal, so the same calculation also handles a miss.
Python documentation for bisect_left and bisect_right
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?