insort function of bisect module in Python

The insort() function computes the insertion point for a new element in an already sorted Python list and inserts the new element in that position. The Python example sorts a list and uses insort() to introduce new elements in their right positions.

Bisect Updated 12 Feb 2020 2 min read

Function Name:

insort

Function Signature

insort(list, newElement, lo=0, hi=len(a))

Parameters

list – A Python list whose elements are already sorted.

newElement – The new element that is to be inserted into the already sorted Python list at the correct position

lo – The lowest index of the search interval to be used as a heuristic. The default value is 0.

hi – The highest index of the search interval to be used as heuristic. The default value is the number of elements present in the list.

Return Value

None

Overview

  • The insort() function inserts a new element into an already sorted Python list.
  • If the list already has existing elements as the new element then the new element is inserted into the right of the last such existing element.
  • The functions insort() and insort_right() behave the same way.
  • Invoking insort() is equivalent to calling the bisect_right() and calling the list.insert().

Example

python
# Example Python program that inserts a new element

# into a Python list whose elements are already sorted

import bisect

import heapq

# Create a list of numbers and sort it in place

elems = [10, 15, 5, 40, 35, 25, 20, 30]

elems.sort()

print("The list:")

print(elems)

# Insert an element which is not present in the list

newElem1 = 45

bisect.insort(elems, newElem1)

print("List after the first insertion using bisect.insort():")

print(elems)

# Insert an element which is present in the list

newElem2 = 25

bisect.insort(elems, newElem2)

print("List after the second insertion using bisect.insort():")

print(elems)

Output

Output
The list:

[5, 10, 15, 20, 25, 30, 35, 40]

List after the first insertion using bisect.insort():

[5, 10, 15, 20, 25, 30, 35, 40, 45]

List after the second insertion using bisect.insort():

[5, 10, 15, 20, 25, 25, 30, 35, 40, 45]