Python | Inserting item in sorted list maintaining order

Working with sorted list is essential because mostly the data we get is ordered. Any query can come to insert the new data into its appropriate position. Hence requires to know how to perform these dynamic queries. Lets discuss certain ways in which this can be performed.

Method #1 : Naive Method
In this method, we just simply test for the value and check if next element is greater than the input element and store the index which is then used to slice in that element at that position.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# insertion in sorted list
# using naive method 
  
# initializing list
test_list = [1, 2, 3, 6, 7]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# insert element
k = 5
  
# using naive method 
# insertion in sorted list
# using naive method 
for i in range(len(test_list)):
    if test_list[i] > k:
        index = i
        break
res = test_list[: i] + [k] + test_list[i :]
  
# printing result
print ("The list after insertion is : " +  str(res))

chevron_right


Output:



The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]

 
Method #2 : Using bisect.insort()
This is more concise and recommended method to perform this particular task. This method is designed for this particular task and performs this task in most efficient manner.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# insertion in sorted list
# using bisect.insort()
import bisect
  
# initializing list
test_list = [1, 2, 3, 6, 7]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# insert element
k = 5
  
# using bisect.insort()
# insertion in sorted list
# using naive method 
bisect.insort(test_list, k) 
  
# printing result
print ("The list after insertion is : " +  str(test_list))

chevron_right


Output:

The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.