bisect

  • find a position in list where an element needs to be inserted to keep the list sorted

Methods

In [35]:
import bisect

l = [5, 6, 1, 3, 4, 4, 6, 7]
l = sorted(l) # [1, 3, 4, 4, 5, 6, 6, 7]

i = bisect.bisect(l, 3) # 2, which is between 3 and 4
l.insert(i, 3) # [1, 3, 3, 4, 4, 5, 6, 6, 7]

bisect.insort(l, 5) # [1, 3, 3, 4, 4, 5, 5, 6, 6, 7], search index and insert