On this page
bisect
Prev: binascii | Up: stdlib_module | Next: builtins
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — bisect
Tags: #public #python3 #stdlib
Import
import bisect
Overview
O(log n) binary search and sorted-insertion utilities for already-sorted sequences (bisect_left, bisect_right, insort_left, insort_right). Ideal for range lookups (grade/tax brackets, timestamp buckets, prefix matching) without building a heavy index structure.
Quick Start
import bisect
scores = [10, 20, 30, 40]
idx = bisect.bisect_left(scores, 25)
assert idx == 2
bisect.insort(scores, 25)
assert scores == [10, 20, 25, 30, 40]
Implementation Walkthrough
1. Bucket / Tier Lookups (Grades, Pricing Tiers, Rate Limits)
import bisect
def letter_grade(score: int) -> str:
breakpoints = [60, 70, 80, 90]
grades = "FDCBA"
return grades[bisect.bisect_right(breakpoints, score)]
assert [letter_grade(s) for s in (55, 60, 79, 90)] == ["F", "D", "C", "A"]
2. Searching Records by Key Function (Python 3.10+)
import bisect
from dataclasses import dataclass
@dataclass(frozen=True)
class Event:
ts: int
label: str
events = [Event(100, "start"), Event(250, "mid"), Event(400, "end")]
i = bisect.bisect_left(events, 250, key=lambda e: e.ts)
assert i < len(events) and events[i].label == "mid"
Gotchas & Boundaries
- The sequence MUST already be sorted:
bisectdoes not verify sorted order and returns silently wrong indices on unsorted input. insort()is O(n) onlist, even though finding the index is O(log n), because inserting into the middle of a Pythonlistshifts trailing elements.bisect_leftvsbisect_right: For an exact match,bisect_leftreturns the index before existing duplicates, whilebisect_right(aliasbisect) returns the index after them.- Always bounds-check the returned index:
bisect_leftcan returnlen(a)when the target is greater than every element.
Common Functions
- bisect.bisect() —
bisect(a, x, lo=0, hi=None, *, key=None)— Return the index where to insert item x in list a, assuming a is sorted. - bisect.bisect_left() —
bisect_left(a, x, lo=0, hi=None, *, key=None)— Return the index where to insert item x in list a, assuming a is sorted. - bisect.bisect_right() —
bisect_right(a, x, lo=0, hi=None, *, key=None)— Return the index where to insert item x in list a, assuming a is sorted. - bisect.insort() —
insort(a, x, lo=0, hi=None, *, key=None)— Insert item x in list a, and keep it sorted assuming a is sorted. - bisect.insort_left() —
insort_left(a, x, lo=0, hi=None, *, key=None)— Insert item x in list a, and keep it sorted assuming a is sorted. - bisect.insort_right() —
insort_right(a, x, lo=0, hi=None, *, key=None)— Insert item x in list a, and keep it sorted assuming a is sorted.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/binascii
- tuts/python3/stdlib_module/builtins
- tuts/python3/stdlib_module/calendar
- tuts/python3/stdlib_module/collections
- tuts/python3/stdlib_module/datetime
- tuts/python3/stdlib_module/heapq
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/zoneinfo
Related notes
- tuts/python3/stdlib_module/binascii Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/datetime Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/zoneinfo Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/bisect/bisect Linked here; shared tags: #stdlib