Write an algorithm / Program to insert a number into a Python List without using insert function
Answers
Answer:
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 program to insert
# an element into sorted list
# Function to insert element
def insert(list, n):
# Searching for the position
for i in range(len(list)):
if list[i] > n:
index = i
break
# Inserting n in the list
list = list[:i] + [n] + list[i:]
return list
# Driver function
list = [1, 2, 4]
n = 3
print(insert(list, n))
Output:
[1, 2, 3, 4]
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 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]
please mark me as brainleast