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.
# 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.
[10, 23, 25, 27, 32]
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.