In Python, the bisect
module in Python assists in preserving a list in sorted order after the insertion of a new element. This is because it bypasses the sort
operation after each insertion.
The bisect()
function of the bisect
module returns the position where we can insert a new element by maintaining the sorted order.
bisect.bisect(list, element,lo=0,hi=len(a))
It takes four parameter values:
list
: This is a sorted Python list.element
: This is the new element that we wish to add.lo
: This is the start index of the list subset. The default value of this parameter is 0
. This is an optional parameter value.hi
: This is the end index of the list subset. The default value of this parameter is the length of the list. This is an optional parameter value.Note: If a new element already exists in the list, the returned position will be to the rightmost of all element occurrences.
import bisect # import bisect module.sorted_list = [1, 2, 3, 4, 5, 7] # sorted list.print (f"given list: {sorted_list}")new_element = 6print(f"new element to be added: {new_element}")print(f"after applying bisect method the index is: {bisect.bisect(sorted_list, new_element)}") # adding new element to the list.existing_element = 7print(f"add an existing element: {existing_element}")print(f"after applying bisect method (add existing element) the index is: {bisect.bisect(sorted_list, existing_element)}") # adding an existing element to the list.
Note:
- The index in python list starts from
0
.- The example above uses f-strings in Python for print statements.
bisect
module.[1, 2, 3, 4, 5, 7]
, and assign it to a variable, sorted_list
. 6
in the new_element
. Next, we apply the bisect
method to the list providing new_element
as an argument. bisect
method to the list that already has the element to be inserted.