On this page
  1. bisect
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Bucket / Tier Lookups (Grades, Pricing Tiers, Rate Limits)
  7. 2. Searching Records by Key Function (Python 3.10+)
  8. Gotchas & Boundaries
  9. Common Functions

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

Common Functions

Linked from

Related notes