Insort_right() function of bisect module in python

Function Name:

insort_right

Function Signature:

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

Parameters:

list – A sorted list

newElement – The new element 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 function insort_right() inserts a new element into an already sorted list.
  • If the list has one or more entries as the new entry it is inserted next to the right most position of such existing entries.
  • Calling insort_right() is equivalent to invoking the function bisect_right() followed by the list.insert() method.

Example:

# Example Python program that inserts new strings

# into an already sorted list of strings using

# bisect.insort_right()

import bisect

 

# Create a list of strings

strings     = ["abc", "xyz", "cba", "bca"]

 

# Sort the list of strings

strings.sort()

print(strings)

 

# Insert a new string

newString   = "tuv"

bisect.insort_right(strings, newString)

print(strings)

 

# Insert the new string one more time

bisect.insort_right(strings, newString)

print(strings)

 

Output:

['abc', 'bca', 'cba', 'xyz']

['abc', 'bca', 'cba', 'tuv', 'xyz']

['abc', 'bca', 'cba', 'tuv', 'tuv', 'xyz']


Copyright 2024 © pythontic.com