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.
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 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)
bisectmodule, which contains methods like
insort_right, and so on.
numsin a sorted order.
ele, which needs to be inserted in the list
elementas 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.
View all Courses