What is bisect.insort_left() in Python?

Overview

In this shot, we’ll learn about the insort_left() 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 automatically put in sorted order.

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

Syntax

import bisect

bisect.insort_left(list, element)

Parameters

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

Example

Let’s look at an example 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 = 50
#insert the element
bisect.insort_left(nums, ele)
#print the nums after inserting the element
print(nums)

Explanation

In the code snippet above:

  • 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 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 insort_left() method, which sorts the list in place after inserting the given element.
  • Line 14: We print the list after inserting the element.

Free Resources