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)- Expected output: 1 [10, 20, 20, 30, 40] False
- 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