Python Bisect Module
The bisect module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work.
Importing the Module
import bisect
Finding Insertion Points
bisect.bisect() (or bisect_right)
Locates the insertion point for x in a to maintain sorted order. If x is already present in a, the insertion point will be after (to the right of) any existing entries.
import bisect
a = [1, 2, 4, 5]
x = 3
# Find position to insert 3
pos = bisect.bisect(a, x)
print(pos) # Output: 2
bisect.bisect_left()
Locates the insertion point for x in a to maintain sorted order. If x is already present in a, the insertion point will be before (to the left of) any existing entries.
import bisect
a = [1, 2, 4, 5]
x = 2
# Find position to insert 2 (left)
pos_left = bisect.bisect_left(a, x)
print(pos_left) # Output: 1
# Find position to insert 2 (right/default)
pos_right = bisect.bisect(a, x)
print(pos_right) # Output: 2
Inserting Elements
bisect.insort() (or bisect.insort_right)
Inserts x in a in sorted order. This is equivalent to a.insert(bisect.bisect(a, x), x).
import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a) # Output: [1, 2, 3, 4, 5]
bisect.insort_left()
Inserts x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x), x).
import bisect
a = [1, 2, 4, 5]
bisect.insort_left(a, 2)
print(a) # Output: [1, 2, 2, 4, 5] (Inserted at index 1)
Examples
Numeric Grades to Letter Grades
The bisect() function can be useful for numeric table lookups.
import bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
print([grade(score) for score in [33, 99, 77, 70, 89, 90, 100]])
# Output: ['F', 'A', 'C', 'C', 'B', 'A', 'A']