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
list: This contains a list of the sorted integers.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 moduleimport bisect#given sorted list of numbersnums = [1,3,5,7,10,25,49,55]#given element to be inserted into the listele = 49#insert the elementbisect.insort_right(nums, ele)#print the nums after inserting the elementprint(nums)
Code explanation
- Line 2: We import the
bisectmodule, which contains methods likeinsort_left,insort_right, and so on. - Line 5: We declare and initialize the list
numsin a sorted order. - Line 8: We are given an element
ele, which needs to be inserted in the listnums. - Line 11: We pass
listandelementas parameters to theinsort_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.