Skip to main content

Sorted List

bisect

  • import bisect
# Insert the item at the left most insertion point in the original array
bisect.insort_left(arr, item, lo=0, hi=len(arr))

# Insert the item at the right most insertion point in the original array
bisect.insort_right(arr, item, lo=0, hi=len(arr))

# Same as bisect.insort_right
bisect.insort(arr, item, lo=0, hi=len(arr))

sortedcontainers

  • import sortedcontainers
sortedList = sortedcontainers.SortedList()

sortedList.add(3) # [3]
sortedList.add(1) # [1, 3]
sortedList.add(2) # [1, 2, 3]

sortedList.remove(2) # [1, 3]

print(sortedList.index(3)) # 1
print(sortedList[-1]) # 3
print(sortedList[0]) # 1
print(4 in sortedList) # false