Codectionary / Developer documentation / Python

Sorted Insertion with bisect

bisect finds insertion boundaries in an already sorted sequence. The returned index is not proof that a value exists. Run as a Python 3.11+ script.

Syntax

bisect_left(items, value); insort(items, value)

Examples

Sorted Insertion with bisect

Run as a Python 3.11+ script.

from bisect import bisect_left, insort
scores = [10, 20, 20, 40]
print(bisect_left(scores, 20))
insort(scores, 30)
index = bisect_left(scores, 25)
print(scores)
print(index < len(scores) and scores[index] == 25)
  1. Expected output: 1 [10, 20, 20, 30, 40] False
  2. bisect_left returns the leftmost valid insertion point. Checking the element at that point distinguishes membership from insertion.

Best practices

  • Keep the list sorted under the same comparison rule.
  • Remember that finding the index is logarithmic but inserting into a Python list is linear.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading