Python | Inserting item in sorted list maintaining order
Last Updated :
24 Apr, 2023
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.
Python3
test_list = [ 1 , 2 , 3 , 6 , 7 ]
print ( "The original list is : " + str (test_list))
k = 5
for i in range ( len (test_list)):
if test_list[i] > k:
index = i
break
res = test_list[: i] + [k] + test_list[i :]
print ( "The list after insertion is : " + str (res))
|
Output
The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]
Time complexity: O(n) where n is size of list
Auxiliary Space: O(n)
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.
Python3
import bisect
test_list = [ 1 , 2 , 3 , 6 , 7 ]
print ( "The original list is : " + str (test_list))
k = 5
bisect.insort(test_list, k)
print ( "The list after insertion is : " + str (test_list))
|
Output
The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]
Time complexity: O(n) where n is size of given list
Auxiliary space: O(1)
Method #3 : Using heapq
To insert an element into a sorted list using a min heap , you can use the following code:
Python3
import heapq
test_list = [ 1 , 2 , 3 , 6 , 7 ]
k = 5
heap = test_list + [k]
heapq.heapify(heap)
sorted_list = [heapq.heappop(heap) for _ in range ( len (heap))]
print (sorted_list)
|
Output
[1, 2, 3, 5, 6, 7]
This code first creates a min heap from the elements of test_list and the element k using the heapq.heapify() function. Then, it extracts the elements from the heap one by one using a list comprehension and the heapq.heappop() function, and stores them in a new list sorted_list, which is then printed.
This approach has a time complexity of O(n log n), since the heapq.heapify() and heapq.heappop() functions have a time complexity of O(n) and O(log n), respectively. It also has a space complexity of O(n), since it requires an additional heap data structure to store the elements.
Method #4 : Using append() and sort() methods
Python3
test_list = [ 1 , 2 , 3 , 6 , 7 ]
print ( "The original list is : " + str (test_list))
k = 5
test_list.append(k)
test_list.sort()
print ( "The list after insertion is : " + str (test_list))
|
Output
The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]
Time Complexity : O(N log N)
Auxiliary Space : O(1)
Method #5 : .insert()
Python3
from bisect import bisect_left
test_list = [ 1 , 2 , 3 , 6 , 7 ]
k = 5
index = bisect_left(test_list, k)
test_list.insert(index, k)
print (test_list)
|
Output
[1, 2, 3, 5, 6, 7]
Time Complexity : O(N)
Auxiliary Space : O(1)
Method #6: Using list comprehension
Python3
test_list = [ 1 , 2 , 3 , 6 , 7 ]
print ( "The original list is : " + str (test_list))
k = 5
res = [x for x in test_list if x < k] + [k] + [x for x in test_list if x > = k]
print (res)
|
Output
The original list is : [1, 2, 3, 6, 7]
[1, 2, 3, 5, 6, 7]
Time Complexity : O(N)
Auxiliary Space : O(N)
Method 7: Using a while loop and comparisons
This method involves using a while loop to find the index at which the new element should be inserted, and then using list slicing and concatenation to insert the element at the correct position.
step by step approach:
- Initialize the list and the new element to be inserted.
- Set a flag variable ‘inserted’ to False.
- Initialize a counter variable ‘i’ to 0.
- While the counter variable ‘i’ is less than the length of the list, do the following:
- a. If the new element is less than or equal to the current element in the list, insert the new element at that position using list slicing and concatenation, set the flag variable ‘inserted’ to True, and break out of the loop.
- b. Otherwise, increment the counter variable ‘i’.
- If the flag variable ‘inserted’ is still False, append the new element to the end of the list.
- Print the original list and the list after insertion.
Python3
test_list = [ 1 , 2 , 3 , 6 , 7 ]
print ( "The original list is : " + str (test_list))
k = 5
inserted = False
i = 0
while i < len (test_list):
if k < = test_list[i]:
test_list = test_list[:i] + [k] + test_list[i:]
inserted = True
break
i + = 1
if not inserted:
test_list.append(k)
print ( "The list after insertion is : " + str (test_list))
|
Output
The original list is : [1, 2, 3, 6, 7]
The list after insertion is : [1, 2, 3, 5, 6, 7]
Time complexity: O(n), where n is the length of the list. In the worst case, the new element has to be inserted at the end of the list, so we have to compare it with every element in the list.
Auxiliary space: O(n), where n is the length of the list. In the worst case, the new element has to be inserted at the beginning of the list, so we have to create a new list of length n+1.
Similar Reads
Get Items in Sorted Order from Given Dictionary - Python
We are given a dictionary where the values are strings and our task is to retrieve the items in sorted order based on the values. For example, if we have a dictionary like this: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} then the output will be ['akshat', 'bhuvan', 'chandan'] Using sorted() with
3 min read
Python Program For Inserting Node In The Middle Of The Linked List
Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
4 min read
Python program to insert an element into sorted list
Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this. Using bisect.insort bisect module provides the insort functio
2 min read
Python | Finding relative order of elements in list
Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive
3 min read
Python Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list. Python Code # Node class class Node: # Function to initialize the # n
7 min read
Python Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read
Sort List of Lists Ascending and then Descending in Python
Sorting a list of lists in Python can be done in many ways, we will explore the methods to achieve the same in this article. Using sorted() with a keysorted() function is a flexible and efficient way to sort lists. It creates a new list while leaving the original unchanged. [GFGTABS] Python a = [[1,
3 min read
How to Convert a List into Ordered Set in Python?
The task is to turn a list into an ordered set, meaning we want to remove any duplicate items but keep the order in which they first appear. In this article, we will look at different ways to do this in Python. Using OrderedDict.fromkeys()OrderedDict.fromkeys() method removes duplicates from a list
2 min read
Python - Convert list of string into sorted list of integer
We are given a list of string a = ['3', '1', '4', '1', '5'] we need to convert all the given string data inside the list into int and sort them into ascending order so the output list becomes a = [1, 1, 3, 4, 5]. This can be achieved by first converting each string to an integer and then sorting the
3 min read
Sorting List of Dictionaries in Descending Order in Python
The task of sorting a list of dictionaries in descending order involves organizing the dictionaries based on a specific key in reverse order. For example, given a list of dictionaries like a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}], the goal
3 min read