What is the bisect.insort() function in Python?
Overview
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.
Parameter values
The bisect.insort() function 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 where we will insert the element. The default value of this parameter is
0. This is an optional parameter value. - Hi: This is the end index of the list subset where we will insert the element. The default value of this parameter is the length of the list. This is an optional parameter value.
Syntax
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))
Code explanation
- Line 1: We import the
bisectmodule. - Line 3: We initialize a sorted list, that is,
[1, 2, 3, 4, 5, 7]and assign it to a variable calledsorted_list. - Lines 7–11: We store the number
6in thenew_element. Then, we add it to the sorted list that was declared above using theinsortmethod, that is,bisect.insort(sorted_list, new_element). - Lines 15–19: We follow the same insertion procedure and insert the existing element in the list, that is,
7using theinsortmethodbisect.insort(sorted_list, existing_element).