insort_left function of bisect module in python

The insort_left() function of bisect module inserts a new element into an already sorted Python list. If the list contains elements with the same value as the new element then the new element is inserted at the left to the first such element.

Bisect Updated 13 Feb 2020 1 min read

Method Name

insort_left

Signature

insort_left(list, newElement, lo, hi)

Parameters

list – The sorted list into which a element is to be inserted at the correct position.

newElement – The element that is to be inserted.

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 method insort_left() of bisect module inserts a new element into an already sorted Python list.
  • If elements with the same value as the new value are present in the list, the new element is inserted at the left of the first such occurrence.
  • Using insort_left(), is equivalent to invoking the bisect.bisect_left() function followed by the list.insert() method.

Example

python
# Example Python program that inserts a new element

# into an already sorted Python list using the

# function bisect.insort_left()

import bisect

# Create a list of numbers

values = [6, 6, 2, 4, 8, 12, 10]

# Sort the list in place

values.sort()

# Print the list

print("Initial list:")

print(values)

# New values to be inserted into the list

newValue1 = 14

newValue2 = 2

# Insert a new element using insort_left()

bisect.insort(values, newValue1)

print("List after the first insert using bisect.insort_left():")

print(values)

# Insert another element using insort_left()

bisect.insort(values, newValue2)

print("List after the second insert using bisect.insort_left():")

print(values)

Output

Output
Initial list:

[2, 4, 6, 6, 8, 10, 12]

List after the first insert using bisect.insort_left():

[2, 4, 6, 6, 8, 10, 12, 14]

List after the second insert using bisect.insort_left():

[2, 2, 4, 6, 6, 8, 10, 12, 14]