
Bisect Module in Python
The bisect
module in Python is a built-in module that provides functions for binary search and insertion into sorted sequences. It allows you to efficiently search for an element in a sorted list or insert an element into a sorted list while maintaining the list’s sorted order. The bisect
module is particularly useful when dealing with large datasets or when you need to perform fast lookups or insertions into sorted collections.
Here are some key functions and classes provided by the bisect
module:
bisect_left(a, x, lo=0, hi=len(a))
: This function finds the index where an elementx
should be inserted into a sorted sequencea
to maintain the sorted order. It returns the leftmost insertion point. If the element is already present, it returns the index of the leftmost occurrence.bisect_right(a, x, lo=0, hi=len(a))
: Similar tobisect_left
, this function finds the rightmost insertion point for elementx
in the sorted sequencea
. It returns the index where the element should be inserted to maintain the sorted order.insort_left(a, x, lo=0, hi=len(a))
: This function inserts elementx
into the sorted sequencea
while maintaining the sorted order. It is equivalent to callinga.insert(bisect_left(a, x, lo, hi), x)
.insort_right(a, x, lo=0, hi=len(a))
: Similar toinsort_left
, this function inserts elementx
into the sorted sequencea
at the rightmost insertion point to maintain the sorted order.
Here’s an example of using the bisect
module to perform binary search and insertion into a sorted list:
import bisect
# Sorted list
sorted_list = [1, 3, 5, 7, 9]
# Perform binary search
index = bisect.bisect_left(sorted_list, 5)
if sorted_list[index] == 5:
print(f"Element 5 found at index {index}")
else:
print("Element 5 not found in the list")
# Insert element into the sorted list
bisect.insort_left(sorted_list, 6)
print("Sorted list after inserting 6:", sorted_list)
This example, we use bisect_left
to find the leftmost insertion point for the element 5 in the sorted list. We then check if the element is already present. Next, we use insort_left
to insert the element 6 into the sorted list while maintaining its sorted order.
The bisect
module is a handy tool for efficiently working with sorted sequences, and it can be particularly useful in various algorithms and data manipulation tasks.