The bisect
module in the standard library provides essential functions for maintaining sorted lists. The various functions provided by the module allow us to perform list operations such as insertions and deletions while ensuring that the list remains in a sorted state. In practice, this is usually much more efficient than repeatedly sorting the list after various operations.
The module provides two basic functions: bisect()
and insort()
. The bisect()
functions finds the position at which an item should be inserted to maintain the list's sorted state, while insort()
actually performs the insertion. Both functions assumes that the input list is already sorted.
The insort()
function also allows us to specify a key
function which it will use to determine the sorting criteria of the input list.
The following example uses the random module to generate random numbers, the bisect insort()
function inserts the numbers in a list in a desceding order.
functions defined in the bisect module
The functions defined in the module are as summarized below.
function | description |
---|---|
bisect(a, x, lo=0, hi=None, key = None) |
Finds the index in the list a where x should be inserted to maintain the sorted state of the list. |
bisect_left(a, x, lo= None, key = None ) |
Just similar to the bisect() function in that it returns the index where x . should be inserted to maintain the sorted state. If x appears in the list it returns the index just before the leftmost value of x already in the list. |
bisect_right(a, x, lo = 0, hi = None, key = None) |
Returns the index where x . should be inserted to maintain the sorted state. If x appears in the list it returns the index just after the rightmost most value of x already in the list. |
insort(a, x, lo = 0, hi = None, key = None) |
Inserts x in the list a while preserving the sorted state of the list. |
insort_left(a, x, lo = 0, hi = None, key = None) |
Uses the bisect_left() function to get the index where to insert element x in list a . |
insort_right(a, x, lo = 0, hi = None, key = None) |
Uses the bisect_right() function to get the index where to insert element x in list a . |
The lo
and hi
parameters in bisect functions refers to the starting and ending indices , respectively. If specified the operation will only happen within the range specified by these indices.