Skip to content
Related Articles

Related Articles

Python program to insert an element into sorted list

View Discussion
Improve Article
Save Article
  • Last Updated : 09 Sep, 2022
View Discussion
Improve Article
Save Article

Given a sorted list and an element, Write a Python program to insert the element into the given list in sorted position. Examples:

Input : list = [1, 2, 4], n = 3
Output : list = [1, 2, 3, 4]

Input : list = ['a', 'b', 'c', 'd'], n = 'e'
Output : list = ['a', 'b', 'c', 'd', 'e']

Approach #1 : This approach is the brute force method. Since the list is already sorted, we begin with a loop and check if the list element is greater than the given element. If yes, the given element need to be inserted at this position. 

Python3




# Python3 program to insert
# an element into sorted list
 
# Function to insert element
 
 
def insert(list, n):
 
    index = len(list)
    # Searching for the position
    for i in range(len(list)):
      if list[i] > n:
        index = i
        break
 
    # Inserting n in the list
    if index == len(list):
      list = list[:index] + [n]
    else:
      list = list[:index] + [n] + list[index:]
    return list
 
# Driver function
list = [1, 2, 4]
n = 3
 
print(insert(list, n))

Output:

[1, 2, 3, 4]

Time Complexity: O(N)
Auxiliary Space: O(1)

  Approach #2 : Python comes with a bisect module whose purpose is to find a position in list where an element needs to be inserted to keep the list sorted. Thus we use this module to solve the given problem. 

Python3




# Python3 program to insert
# an element into sorted list
import bisect
 
def insert(list, n):
    bisect.insort(list, n)
    return list
 
# Driver function
list = [1, 2, 4]
n = 3
 
print(insert(list, n))

Output:

[1, 2, 3, 4]

Time Complexity: O(N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!