bisect

In [2]:
from bisect import insort_right, bisect_right

bisect is used to efficiently insert items into sorted lists (saving significant time and memory for long lists).

  • bisect_left and bisect_right find insertion points in a list.
  • bisect_left starts from the lefthand side and bisect_right from the righthand.
  • bisect is the same as bisect_right
  • Optional parameters lo and hi can be used to restrict the search range.
  • insort_left and insort_right perform the insertion in place.
  • insort is the same as insort_right
In [3]:
a = [1, 3, 4, 5, 7, 8, 12, 14, 34, 45]
In [4]:
insort_right(a, 17)
a
Out[4]:
[1, 3, 4, 5, 7, 8, 12, 14, 17, 34, 45]
In [5]:
insort_right(a, 9, 5, 10)
a
Out[5]:
[1, 3, 4, 5, 7, 8, 9, 12, 14, 17, 34, 45]
In [6]:
grades = 'FEDCBA'
grade_boundaries = [30, 44, 66, 75, 85]
def grade(total):
    return grades[bisect_right(grade_boundaries, total)]
In [7]:
grade(35)
Out[7]:
'E'
In [8]:
grades[bisect_right(grade_boundaries, 35)]
Out[8]:
'E'