The bisect module is written in python and here is the source code
What it does?
The bisect module in Python provides support for maintaining a list in sorted order without having to sort the list after each insertion. It uses a binary search algorithm to find the insertion point for a given element in a sorted list, which is more efficient than linear search.
Key functions provided by the bisect module:

bisect.bisect_left(list, num, beg, end)
: This function returns the sorted list after inserting the number in the appropriate position. If the element already exists, then the element is inserted at the leftmost possible position. import bisect
list = [1, 3, 4, 4, 6, 7]
bisect.bisect_left(list, 5)
print(list) # Output: [4]

bisect.bisect_right(list, num, beg, end)
: This function works similar tobisect_left()
, but if the element already exists, then the rightmost position is returned.bisect.bisect()
is an alias forbisect_right()
. import bisect
list = [1, 3, 4, 4, 4, 6, 7]
print(bisect.bisect_right(list, 4)) # Output: 5

bisect.insort_left(list, num, beg, end)
: This function returns the sorted list after inserting the number in the appropriate position. If the element already exists, then the element is inserted at the leftmost possible position.
import bisect
list = [1, 3, 4, 4, 6, 7]
bisect.insort_left(list, 5)
print(list) # Output: [1, 3, 4, 4, 5, 6, 7]

bisect.insort_right(list, num, beg, end)
: This function works similar toinsort_left()
, but if the element already exists, then the element is inserted at the rightmost possible position.bisect.insort()
is an alias forinsort_right()
.
import bisect
list = [1, 3, 4, 4, 6, 7]
bisect.insort_right(list, 4)
print(list) # Output: [1, 3, 4, 4, 4, 6, 7]
In all these functions, beg and end are optional arguments specifying the range in which to search for the insertion point. If omitted, the entire list is used.
If you have any feedback, then you can DM me on Twitter or Linkedin.
Top comments (0)