bisect Inserts While Keeping Sort Order
Maintain sorted lists with bisect: insort places items in order, bisect_left and bisect_right answer range questions, and key compares by projection.
Code
import bisect
# bisect 维护「已排序列表」的不变量:插入点即查找点
thresholds = [10, 50, 100, 500]
# insort 按序插入,无需先 append 再 sort
bisect.insort(thresholds, 75)
print(thresholds)
# bisect_right 给出插入点:右起第一个大于 amount 的位置
amount = 120
idx = bisect.bisect_right(thresholds, amount)
print(f"amount {amount} falls in tier {idx - 1}")
# key 参数(3.10+):对 (priority, task) 元组按第一维比较
jobs = [(3, "cleanup"), (1, "backup"), (2, "index")]
jobs.sort()
bisect.insort(jobs, (2, "report"))
print(jobs)
# 与手写二分等价:实现经过优化,语义只有一处定义
print(bisect.bisect_left(thresholds, 50), bisect.bisect_right(thresholds, 50))Output
Captured from a sandboxed run of this snippet in the build pipeline.
[10, 50, 75, 100, 500]
amount 120 falls in tier 3
[(1, 'backup'), (2, 'index'), (2, 'report'), (3, 'cleanup')]
1 2How it works
Module-level bindings hold the data — thresholds, amount, idx, jobs — with no function scope in between.
What to watch for
- Nothing to install:
bisectships with the Python standard library.
Using it
Running the file prints labeled results such as amount — each operation’s effect is visible in the output.
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `bisect`. Its state lives in module-level bindings: `thresholds`, `amount`, `idx`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.