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:

  1. List: This is a sorted Python list.
  2. Element: This is the new element that we wish to add.
  3. 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.
  4. 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 = 6
print("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 = 7
print("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 bisect module.
  • Line 3: We initialize a sorted list, that is, [1, 2, 3, 4, 5, 7] and assign it to a variable called sorted_list.
  • Lines 7–11: We store the number 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).
  • Lines 15–19: We follow the same insertion procedure and insert the existing element in the list, that is, 7 using the insort method bisect.insort(sorted_list, existing_element).

Free Resources