Python bisect — bisect_left, bisect_right, and insort
Searching a sorted list by scanning from the start wastes the order the list already has. The bisect module finds the insertion point for a value with a binary search, so a program can test membership, count duplicates, read a range, and insert new items while the list stays sorted. This guide takes the left and right forms first, then insertion, duplicates, the key form, a grade table built on breakpoints, bounded searches, and the unsorted-list trap.
Written November 13, 2026 · Tested with Python 3.12.3 · 9 min read
- The main program: left, right, and the insertion point
- insort: inserting while the list stays sorted
- Duplicates: counting and slicing equal values
- The key form: searching tuples by one field
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
The bisect module works on a list that is already in sorted order. It answers one question: at which index would a value belong in this list? That index supports several jobs at once. A membership test compares the item at the index with the value. A count of duplicates subtracts one index from another. A range read slices between two indexes. An insertion puts the value at its index, and the list stays sorted for the next search. None of this repairs an unsorted list, and none of it sorts one. The order is the input, and the module keeps it.
The main program: left, right, and the insertion point
bisect_left returns the first index at which a value could sit. bisect_right returns the index just past any items equal to the value. The plain name bisect is the right form under a shorter name. A value that is absent still gets an index, the place it would occupy if it were inserted:
import bisect
scores = [10, 20, 20, 30, 40, 50]
print(bisect.bisect_left(scores, 20))
print(bisect.bisect_right(scores, 20))
print(bisect.bisect(scores, 20))
print(bisect.bisect_left(scores, 25))
print(bisect.bisect_left(scores, 5))
print(bisect.bisect_right(scores, 50))
The exact output:
1
3
3
3
0
6
The value 20 appears at indexes 1 and 2, so the left form gives 1 and the right form gives 3. The value 25 is absent, and both forms would agree on 3, between 20 and 30. A value below every item gives 0, and a value above every item gives the length of the list. That last point matters in code: the returned index can equal the length, so a membership test must check the index is in range before reading the item at it.
insort: inserting while the list stays sorted
The insort function finds the insertion point and inserts the value there in one call. Building a list by repeated insertion keeps it sorted after each step, as the printed steps show. The left form places a new item before equal items, and the right form places it after them:
import bisect
scores = []
for value in [30, 10, 40, 20, 20]:
bisect.insort(scores, value)
print(scores)
bisect.insort_left(scores, 20)
print(scores)
bisect.insort_right(scores, 25)
print(scores)
The exact output:
[30]
[10, 30]
[10, 30, 40]
[10, 20, 30, 40]
[10, 20, 20, 30, 40]
[10, 20, 20, 20, 30, 40]
[10, 20, 20, 20, 25, 30, 40]
The search step is fast, but the insert step still moves the later items in the list to make room. For a list that gains an item now and then, that cost is minor. For a stream of many items, collecting the items first and sorting the whole list once at the end states the job more directly. The choice turns on how often the code must search between inserts: a list that is searched after each insert earns the insertion cost, and a list that is searched only once at the end does not.
Duplicates: counting and slicing equal values
With duplicate values, the gap between the left and right indexes is the count of that value. Slicing between the two indexes returns exactly the equal items. The same pair of calls reads a span between two different values, from the first index of the lower value to the end of the upper one:
import bisect
values = [5, 10, 10, 10, 15, 20]
left = bisect.bisect_left(values, 10)
right = bisect.bisect_right(values, 10)
print(left)
print(right)
print(right - left)
print(values[left:right])
print(bisect.bisect_left(values, 12))
print(values[bisect.bisect_left(values, 12):bisect.bisect_right(values, 15)])
The exact output:
1
4
3
[10, 10, 10]
4
[15]
The count of 10 is 3, read off as 4 minus 1 without scanning the list. The last line starts at the insertion point for 12, which is index 4, and ends just past 15, so the slice holds only the 15. Code that asks how many times a value occurs, or that needs every copy of it, uses this pair as its first step instead of a loop over the whole list.
The key form: searching tuples by one field
Since Python 3.10, the search and insert functions accept a key function. The key states which part of each item the search compares, so a list of tuples sorted by one field can be searched by that field alone. The list itself must be sorted by the same key:
import bisect
students = [("Ana", 73), ("Ben", 88), ("Cid", 88), ("Dee", 95)]
print(bisect.bisect_left(students, 88, key=lambda s: s[1]))
print(bisect.bisect_right(students, 88, key=lambda s: s[1]))
print(bisect.bisect_left(students, 80, key=lambda s: s[1]))
bisect.insort(students, ("Eli", 80), key=lambda s: s[1])
print(students)
names = ["ana", "ben", "cid", "dee"]
print(bisect.bisect_left(names, "bea"))
print(bisect.bisect_left(names, "ben"))
The exact output:
1
3
1
[('Ana', 73), ('Eli', 80), ('Ben', 88), ('Cid', 88), ('Dee', 95)]
1
1
The score 88 spans indexes 1 and 2, so the left form gives 1 and the right form gives 3, the same duplicate shape as plain numbers. The new student with a score of 80 lands between 73 and 88, and the list stays in score order. The last two lines search plain text: a name that would sit between two present names gives the index of the next one, and a present name gives its own index.
Breakpoints: a grade from a score
A sorted list of breakpoints turns a search into a table lookup. The right form counts how many breakpoints a score reaches or passes, and that count indexes into the labels. Each breakpoint belongs to the label above it, so a score of exactly 60 takes the second label, not the first:
import bisect
breakpoints = [60, 70, 80, 90]
grades = "FDCBA"
def grade(score):
return grades[bisect.bisect(breakpoints, score)]
for score in [33, 60, 65, 70, 79, 80, 89, 90, 100]:
print(score, grade(score))
The exact output:
33 F
60 D
65 D
70 C
79 C
80 B
89 B
90 A
100 A
The boundary rows carry the rule. A score just below a breakpoint takes the lower label, and a score on the breakpoint takes the higher one, because the right form counts that breakpoint as passed. Price bands, size bands, and age bands follow the same shape: one sorted list of cut points, one list of labels with one more entry than the cut list, and the search result as the label index.
Bounds: searching part of the list
The lo and hi arguments limit the search to a slice of the list. The indexes returned are still positions in the full list, not in the slice. Bounds suit code that already knows a value can only sit in one region, or that reads successive ranges from one list:
import bisect
times = [5, 12, 12, 20, 31, 45, 60]
lo = bisect.bisect_left(times, 12)
hi = bisect.bisect_right(times, 31)
print(lo)
print(hi)
print(times[lo:hi])
print(bisect.bisect_left(times, 12, lo=2))
print(bisect.bisect_right(times, 12, hi=2))
print(bisect.bisect_left(times, 100))
The exact output:
1
5
[12, 12, 20, 31]
2
2
7
The first slice reads every item from 12 through 31. Starting the search at index 2 skips the first 12 and finds the second one, and ending the search at index 2 counts only the items before that point. A search for a value above every item returns the length of the list, 7 here, which a slice accepts as its end without an error.
The unsorted trap, and a safe membership test
import bisect
unsorted = [30, 10, 20]
print(bisect.bisect_left(unsorted, 15))
print(sorted(unsorted))
print(bisect.bisect_left(sorted(unsorted), 15))
values = [10, 20, 30]
index = bisect.bisect_left(values, 20)
print(index)
print(index < len(values) and values[index] == 20)
index = bisect.bisect_left(values, 25)
print(index < len(values) and values[index] == 25)
The exact output:
2
[10, 20, 30]
1
1
True
False
On the unsorted list the search claims 15 belongs at index 2; on the sorted list it belongs at index 1. Code that receives a list from elsewhere sorts it first, or keeps the list sorted from the start with insort, and never assumes. The last lines give the membership test in its safe form: the index is checked against the length before the item is read, and the item is compared with the value, so an absent value returns False instead of an error or a false match on the next item.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| First index of a value | bisect_left | Lands before equal items |
| End of a run of equals | bisect_right | Lands past equal items |
| Count a value | Right minus left | Gap is the count |
| Insert and stay sorted | insort |
Search and insert in one call |
| Search tuples by a field | key form | Compares one field only |
| Label from cut points | bisect on breakpoints | Count indexes the labels |
| Full sort of new data | sorted | bisect never sorts |
Checklist
- Search only a list that is sorted by the same order the search uses; sort first or build with
insort. - Use bisect_left for the first index of a value and bisect_right for the index past its last copy.
- Check the returned index against the length before reading the item in a membership test.
- Pass the same key to the search that the list was sorted by.
- Remember that
insortstill moves later items; sort once at the end when no search happens between inserts. - Treat a breakpoint as belonging to the label above it when the right form does the lookup.
Related guides on this site
- Python sorting — sorted, sort, and key — putting a list into the sorted order that every search in this guide assumes.
- Python heapq — heapify, heappush, heappop, and nlargest — the smallest-first structure, where this guide covers searching a fully sorted list.
- Python lists, dicts, and sets — the list operations this guide builds on, including slicing between two indexes.
Sources
- Python Standard Library, bisect — bisect_left, bisect_right,
insort, the key and lo/hi arguments, and the grade example shape. - Python HOWTO, Sorting — key functions and the sorted order a bisect search relies on.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.