Python - Inserting item in sorted list maintaining order


In this article, we are going to learn how to insert an item in a sorted list maintaining the order. Python has a built-in module called bisect that helps us to insert any element in an appropriate position in the list.

Follow the below steps to write the code.

  • Import the module bisect.
  • Initialize list and element that need to insert
  • The module bisect has a method called insort that inserts an element into a list in an appropriate position. Use the method and insert the element.
  • Print the list.

Example

 Live Demo

# importing the module
import bisect

# initializing the list, element
numbers = [10, 23, 27, 32]
element = 25

# inserting element using bisect.insort(list, element)
bisect.insort(numbers, element)

# printing the list
print(numbers)

If you run the above code, then you will get the following result.

Output

[10, 23, 25, 27, 32]

Conclusion

We can iterate over the list and find the position to insert an element into the correct position. That's not an efficient way to do it. The insort method handles it more efficiently.

Updated on: 13-Nov-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements