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.
import bisect
bisect.insort_right(list, element)
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.
#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)
bisect
module, which contains methods like insort_left
, insort_right
, and so on.nums
in a sorted order.ele
, which needs to be inserted in the list nums
.list
and element
as parameters to the insort_right()
method, which sorts the list in place after inserting the given 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.