What is bisect.bisect_right() in Python?

Overview

In this shot, we’ll learn about the bisect_right() method in Python.

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

Syntax

import bisect

bisect.bisect_right(list, element)

Parameters

  1. list: Contains a list of sorted integers.
  2. element: Provides an element that needs to be inserted into the sorted list.

Return value

The bisect_right() method is provided by the bisect module, which returns the right-most index to insert the given element while maintaining the sorted order.

Example

Let’s look at an example below to understand this better:

#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 = 25
#get index where to insert the element
idx = bisect.bisect_right(nums, ele)
#print the index
print(f"Insert element {ele} at index {idx} in nums list to maintain sorted order.")

Explanation

In the code snippet above:

  • Line 2: We import the bisect module, which contains methods like bisect_right, bisect_left, and so on.
  • Line 5: We declare and initialize the list nums in sorted order.
  • Line 8: We are given an element ele to be inserted in the list nums.
  • Line 11: We pass list and element as parameters to the bisect_right() method, which returns an index.
  • Line 14: We print the returned index.

Output

The output tells us to insert the element at index 6 because an element 25 is already present in the list. Since we use the bisect_right() method, it suggests inserting the element at the rightmost position.