The bisect
module in Python assists in preserving a list in a sorted order, as it bypasses the sort operation after each insertion. Insort
is one of the functions of the bisect
module.
The bisect.insort()
function takes four parameter values:
0
. This is an optional parameter value.bisect.insort(list, element, lo=0, hi=len(a))
Note: If the list already has the new element which we wish to add, then it will be inserted to the right of the last occurrence of that element.
Let’s check out an example where we consider a sorted list to add a new element using the insort
function. We will also look at the scenario where we add the element that is already present in the list.
import bisect # import bisect module.sorted_list = [1, 2, 3, 4, 5, 7] # sorted list.print ("given list: {}".format(sorted_list))new_element = 6print("new element to be added: {}".format(new_element))bisect.insort(sorted_list, new_element) # adding new element to the list.print("after applying insort method: {}".format(sorted_list))existing_element = 7print("add an existing element: {}".format(existing_element))bisect.insort(sorted_list, existing_element) # adding an existing element to the list.print("after applying insort method (add existimg element): {}".format(sorted_list))
bisect
module.[1, 2, 3, 4, 5, 7]
and assign it to a variable called sorted_list
.6
in the new_element
. Then, we add it to the sorted list that was declared above using the insort
method, that is, bisect.insort(sorted_list, new_element)
.7
using the insort
method bisect.insort(sorted_list, existing_element)
.