![]() |
VOOZH | about |
The bisect module is used to locate positions in a sorted list and insert elements while maintaining order. It works using binary search and helps determine where a value fits within an existing sorted sequence.
The bisect module mainly offers two types of functionalities, as listed below:
These functions return the index at which the new element should be inserted to maintain the list's sorted order.
1. bisect.bisect(): Returns the rightmost insertion point for the element. If the element already exists, the insertion point will be after the existing entries.
bisect.bisect(list, num, beg=0, end=len(list))
Parameters:
Example: In this example, we find the rightmost position where the value 4 should be inserted in a sorted list.
4 3
Explanation:
2. bisect.bisect_left(): Returns the leftmost insertion point for the element. If the element exists, the insertion point will be before the existing entries.
bisect.bisect_left(list, num, beg=0, end=len(list))
Example: Here, we find the leftmost position where the value should be inserted.
2 4
Explanation:
3. bisect.bisect_right(): Identical to bisect.bisect(), returns the rightmost insertion point.
bisect.bisect_right(list, num, beg=0, end=len(list))
Example: In this code, we find the rightmost insertion position similar to bisect().
4 4
Explanation:
These functions insert the element at the proper position to maintain sorting.
1. bisect.insort(): Inserts the element at the rightmost position. Unlike bisect() functions, this actually modifies the list by inserting the element.
bisect.insort(list, num, beg=0, end=len(list))
Example: Here, we insert a new value into the list while keeping it sorted.
[1, 3, 4, 5, 6]
Explanation: insort(li, 5) inserts 5 at correct sorted position
2. bisect.insort_left(): Inserts the element at the leftmost position.
bisect.insort_left(list, num, beg=0, end=len(list))
Example: In this example, we insert a value at the leftmost valid position.
[1, 3, 4, 4, 4, 6]
Explanation: insort_left(li, 4) inserts 4 before existing 4s
3. bisect.insort_right(): Inserts the element at the rightmost position (similar to insort()).
bisect.insort_right(list, num, beg=0, end=len(list))
Example: Here, we insert a value at the rightmost position within a given range.
[1, 3, 4, 4, 5, 6]
Explanation: