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.

PythonData Integrity

Code

pythonsnippet
22 lines
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 2

How 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: bisect ships 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

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`.