What is bisect.insort_right() in Python?

Overview

In this shot, we will learn about the insort_right() method in Python. Let’s start by looking at when we need this method.

We may want to insert an element in a sorted list, but we may still want to maintain the sort order after insertion. It will be a costly operation if we do this operation over a long list. In this situation, we can use the bisect module, which ensures that the list is automatically put in a sorted order.

The insort_right() method is provided by the bisect module, which sorts the list in place after inserting the given element. If the element is already present in the list, it inserts the element at the right-most position.

Syntax

import bisect

bisect.insort_right(list, element)

Parameters

  1. list: This contains a list of the sorted integers.
  2. element: This provides the element that needs to be inserted into the sorted list.

Let’s look at an example to better understand this.

Code example

#import the module
import bisect
#given sorted list of numbers
nums = [1,3,5,7,10,25,49,55]
#given element to be inserted into the list
ele = 49
#insert the element
bisect.insort_right(nums, ele)
#print the nums after inserting the element
print(nums)

Code explanation

  • Line 2: We import the bisect module, which contains methods like insort_left, insort_right, and so on.
  • Line 5: We declare and initialize the list nums in a sorted order.
  • Line 8: We are given an element ele, which needs to be inserted in the list nums.
  • Line 11: We pass list and element as parameters to the insort_right() method, which sorts the list in place after inserting the given element.
  • Line 14: We print the list after inserting the element.

The element is inserted at index 7. Since the element 49 is already present in the list and because we are using the insort_right method to insert, the element is inserted at the rightmost position.