Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Insert list in another list

Python | Insert list in another list

The problem of inserting a number at any index is a quite common one. But sometimes we require to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. Let’s discuss certain ways in which this problem can be solved.

Method #1: Using insert() + loop In this method, we insert one element by 1 at a time using the insert function. This way we add all the list elements at the specified index in other list. 

Step-by-step approach:

  • Use a for loop to iterate over the elements of the insert_list.
  • Use the insert() method of the test_list to insert each element of the insert_list at the appropriate position, calculated using the formula i + pos, where i is the index of the current element in the insert_list.
  • Print the updated test_list using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# to insert one list in another
# using insert() + loop
 
# initializing lists
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
 
# initializing position
pos = 2
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing insert list
print ("The list to be inserted is : " + str(insert_list))
 
# using insert() + loop
# to insert one list in another
for i in range(len(insert_list)):
    test_list.insert(i + pos, insert_list[i])
 
# printing result
print ("The list after insertion is : " + str(test_list))


Output

The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

Time Complexity: O(n*m) where n is the number of elements in the test_list and m is the number of elements in the insert_list.
Auxiliary Space: O(n)

Method #2: Using list slicing This is the most pythonic and elegant way to perform this particular task. In this method, we just slice the list where we need to add the element and assign the list to be inserted. 

Python3




# Python3 code to demonstrate
# to insert one list in another
# using list slicing
 
# initializing lists
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
 
# initializing position
pos = 2
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing insert list
print ("The list to be inserted is : " + str(insert_list))
 
# using list slicing
# to insert one list in another
test_list[pos:pos] = insert_list
 
# printing result
print ("The list after insertion is : " + str(test_list))


Output

The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

Time complexity: O(n), where n is the length of test_list + the length of insert_list. 
Auxiliary space: O(n), where n is the length of the resulting list after the insertion. 

Method #3 : Use + and slicing for inserting

To insert a list into another list using + and slicing, you can use the following approach:

Python3




# Initialize the lists
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
 
# Initialize the position where the insert_list should be inserted
pos = 2
 
# Print the original list
print("The original list is:", test_list)
 
# Print the list to be inserted
print("The list to be inserted is:", insert_list)
 
# Insert the insert_list into the test_list using + and slicing
test_list = test_list[:pos] + insert_list + test_list[pos:]
 
# Print the resulting list
print("The list after insertion is:", test_list)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is: [4, 5, 6, 3, 9]
The list to be inserted is: [2, 3]
The list after insertion is: [4, 5, 2, 3, 6, 3, 9]

The time complexity of the + operator and slicing approach for inserting a list into another list is O(n), where n is the length of the list being inserted. This is because each element of the list being inserted must be individually appended to the target list.

The space complexity of this approach is also O(n), as a new list with a length of n is created in memory to hold the elements of the inserted list.

Method #4 : Using insert(),replace(),split(),list(),map() methods

Python3




# Initialize the lists
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
 
# Initialize the position where the insert_list should be inserted
pos = 2
 
# Print the original list
print("The original list is:", test_list)
 
# Print the list to be inserted
print("The list to be inserted is:", insert_list)
 
# Insert the insert_list into the test_list using + and slicing
test_list.insert(pos,insert_list)
x=str(test_list)
x=x.replace("[","")
x=x.replace("]","")
a=x.split(",")
a=list(map(int,a))
# Print the resulting list
print("The list after insertion is:", a)


Output

The original list is: [4, 5, 6, 3, 9]
The list to be inserted is: [2, 3]
The list after insertion is: [4, 5, 2, 3, 6, 3, 9]

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

Method#5: Using Recursive method.

Algorithm:

  1. Define a recursive function that takes three parameters – the original list, the list to be inserted, and the position at which to insert the list.
  2. If the insert list is empty, return the original list.
  3. If the position is greater than the length of the original list, concatenate the original list and the insert list and return the result.
  4. Otherwise, remove the first element from the insert list and insert it into the original list at the specified position.
  5. Call the recursive function with the updated original list, remaining insert list, and the incremented position.
  6. Return the result from the recursive call.

Python3




def insert_list_recursive(test_list, insert_list, pos, i=0):
  if i == len(insert_list):return test_list
  else:test_list.insert(i + pos, insert_list[i])
  return insert_list_recursive(test_list, insert_list, pos, i+1)
 
#initializing lists
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
 
#initializing position
pos = 2
 
#printing original list
print ("The original list is : " + str(test_list))
 
#printing insert list
print ("The list to be inserted is : " + str(insert_list))
 
#using recursive function
#to insert one list in another
test_list = insert_list_recursive(test_list, insert_list, pos)
 
#printing result
print ("The list after insertion is : " + str(test_list))
#this code contributed by tvsk


Output

The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

Time complexity: O(n^2) in the worst case (when inserting at the beginning of the list) due to the cost of shifting the remaining elements in each iteration.
Auxiliary space: O(n) in the worst case, due to the recursion stack.

Method#6: Using the chain() function from the itertools module:

1.Initialize the original list test_list, list to be inserted insert_list and position pos where the insert_list should be inserted.
2.Print the original list and the list to be inserted.
3.Use chain method from itertools to chain the elements of the original list sliced till the position where the insert_list should be inserted, followed by the insert_list, and then the remaining elements of the original list sliced from the position where insert_list should be inserted.
4.Convert the resulting iterator object to a list.
5.Print the resulting list.

Python3




from itertools import chain
 
# Initialize the original list
test_list = [4, 5, 6, 3, 9]
 
# Initialize the list to be inserted
insert_list = [2, 3]
 
# Initialize the position where the insert_list should be inserted
pos = 2
 
# Print the original list
print("The original list is:", test_list)
 
# Print the list to be inserted
print("The list to be inserted is:", insert_list)
 
# Insert the insert_list into the test_list using chain and slicing
test_list = list(chain(test_list[:pos], insert_list, test_list[pos:]))
 
# Print the resulting list
print("The list after insertion is:", test_list)
#This code is contributed by Jyothi pinjala.


Output

The original list is: [4, 5, 6, 3, 9]
The list to be inserted is: [2, 3]
The list after insertion is: [4, 5, 2, 3, 6, 3, 9]

Time Complexity: O(n), where n is the length of the original list since we are slicing the list at the position where the insert_list should be inserted, and then concatenating it with the insert_list, and then concatenating it with the remaining part of the original list.

Space Complexity: O(n), where n is the length of the original list since we are creating a new list to store the resulting list after concatenation.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments