Python | Insert Nth element to Kth element in other list
Last Updated :
02 May, 2023
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed.
Method 1: Using pop() + insert() + index()
This particular task can be performed using a combination of the above functions. In this, we just use the property of pop function to return and remove the element and insert it to the specific position of the other list using the index function.
Python3
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
N = 5
K = 3
res = test_list1.insert(K, test_list2.pop(N))
print ( "The list 1 after insert is : " + str (test_list1))
print ( "The list 2 after remove is : " + str (test_list2))
|
Output :
The original list 1 is : [4, 5, 6, 7, 3, 8]
The original list 2 is : [7, 6, 3, 8, 10, 12]
The list 1 after insert is : [4, 5, 6, 12, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
Time Complexity: O(n), n is the length of the list.
Auxiliary Space: O(1)
Method 2: Using slicing and concatenation
This approach involves slicing the original list1 into two parts, the first part contains the elements before the Kth position, and the second part contains the elements after the Kth position. Then, we concatenate the first part, the Nth element of list2, and the second part using the + operator to form a new list. Finally, we print the updated list1 and the remaining elements of list2.
Approach:
- Creates a new list res by taking a slice of test_list1 from the beginning up to the Kth element (exclusive), concatenating it with a list containing the Nth element of test_list2, and concatenating that with a slice of test_list1 from the Kth element to the end. This effectively inserts the Nth element of test_list2 into the Kth position of test_list1.
- Prints the resulting list res using the print() function.
- The program creates a new list by taking a slice of test_list2 from the beginning up to the Nth element (exclusive), concatenating it with a slice of test_list2 from the N+1th element to the end. This effectively removes the Nth element from test_list2.
- Prints the resulting list using the print() function.
Below is the implementation of the above approach:
Python3
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
N = 5
K = 3
res = test_list1[:K] + [test_list2[N]] + test_list1[K:]
print ( "The list 1 after insert is : " + str (res))
print ( "The list 2 after remove is : " + str (test_list2[:N] + test_list2[N + 1 :]))
|
Output
The list 1 after insert is : [4, 5, 6, 12, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
Time complexity: O(n), where n is the length of the lists.
Auxiliary space: O(n), where n is the length of the lists.
Method 3: using list comprehension
Here’s a step-by-step approach:
- Initialize two lists test_list1 and test_list2:
- Initialize two variables N and K:
- Use list comprehension to create a new list res that contains the first K elements of test_list1, the element from test_list2 at index N, and the remaining elements of test_list1:
- Print the updated lists:
Python3
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
N = 5
K = 3
res = [test_list1[i] for i in range (
K)] + [test_list2[N]] + [test_list1[i] for i in range (K, len (test_list1))]
print ( "The list 1 after insert is : " + str (res))
print ( "The list 2 after remove is : " + str (test_list2[:N] + test_list2[N + 1 :]))
|
Output
The list 1 after insert is : [4, 5, 6, 12, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
Time complexity: O(n), where n is the length of the lists.
Auxiliary space: O(n) as well, since we are creating a new list.
Method#4: Using the Recursive method
In this recursive method, we use two input lists test_list1 and test_list2, an integer N indicating the index of the element to remove from test_list2, and an integer K indicating the index of the element in test_list1 to insert before the N-th element of test_list2.
In the base case, when N is 0, we return a new list with the first element of test_list2 followed by all the elements of test_list1.
In the recursive case, we first check if K is 0. If it is, we return a new list with the N-th element of test_list2 followed by the result of recursively calling insert_remove with test_list1 and test_list2 but with N decreased by 1 and K set to 0.
If K is not 0, we return a new list with the first element of test_list1 followed by the result of recursively calling insert_remove with the rest of test_list1, the same test_list2, the same N, and K decreased by 1.
Finally, we can call the insert_remove function with the input lists and indices to get the result. Note that this implementation assumes that K and N are valid indices for the input lists, and does not perform any input validation or error checking.
Python3
def insert_remove(test_list1, test_list2, N, K):
if N = = 0 :
return [test_list2[ 0 ]] + test_list1
if K = = 0 :
return [test_list2[N]] + insert_remove(test_list1, test_list2, N - 1 , 0 )
else :
return [test_list1[ 0 ]] + insert_remove(test_list1[ 1 :], test_list2, N, K - 1 )
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
N = 5
K = 3
res = insert_remove(test_list1, test_list2, N, K)
print ( "The list 1 after insert is : " + str (res))
print ( "The list 2 after remove is : " + str (test_list2[:N] + test_list2[N + 1 :]))
|
Output
The list 1 after insert is : [4, 5, 6, 12, 10, 8, 3, 6, 7, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
The time complexity of the recursive method is O(N+K) where N is the length of test_list2 and K is the position of the element to be inserted in test_list1. This is because each recursive call either decreases N or K by 1 until we reach the base case where N is 0.
The space complexity of the recursive method is O(N+K) as well since each recursive call creates a new list with a total of N+K elements. However, since Python has a recursion limit, the maximum depth of the recursion is limited by the system and may cause a runtime error if the limit is exceeded.
Method #5: Using the extend() method
Here’s the step-by-step approach:
- Initialize two lists: test_list1 and test_list2.
- Print the original lists using the print() function.
- Initialize two variables: N and K.
- Use the extend() method to insert the Nth element from test_list2 into test_list1 at the Kth position.
- Print the updated test_list1 and test_list2 using the print() function.
Python3
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
N = 5
K = 3
test_list1[K:K] = [test_list2.pop(N)]
print ( "The list 1 after insert is : " + str (test_list1))
print ( "The list 2 after remove is : " + str (test_list2))
|
Output
The original list 1 is : [4, 5, 6, 7, 3, 8]
The original list 2 is : [7, 6, 3, 8, 10, 12]
The list 1 after insert is : [4, 5, 6, 12, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
Time Complexity: O(n), where n is the length of test_list2.
Auxiliary Space: O(1), as we are only using a constant amount of extra memory for the variables N and K.
Method #6: Using the itertools module
This approach involves using the itertools.chain() function to concatenate the first K elements of test_list1, the (N-K) elements of test_list2 before the Nth element, the Nth element of test_list2, and the remaining elements of test_list1:
- Import the itertools module.
- Use the chain() function to concatenate the following four iterators:
- The first K elements of test_list1, obtained using slicing.
- The (N-K) elements of test_list2 before the Nth element, obtained using slicing.
- The Nth element of test_list2, obtained using indexing.
- The remaining elements of test_list1, obtained using slicing.
- Convert the iterator returned by chain() into a list using the list() function.
- Assign the resulting list to a variable called res.
Python3
import itertools
test_list1 = [ 4 , 5 , 6 , 7 , 3 , 8 ]
test_list2 = [ 7 , 6 , 3 , 8 , 10 , 12 ]
N = 5
K = 3
res = list (itertools.chain(test_list1[:K], test_list2[K:N], test_list2[N:N + 1 ], test_list1[K:]))
print ( "The list 1 after insert is : " + str (res))
print ( "The list 2 after remove is : " + str (test_list2[:N] + test_list2[N + 1 :]))
|
Output
The list 1 after insert is : [4, 5, 6, 8, 10, 12, 7, 3, 8]
The list 2 after remove is : [7, 6, 3, 8, 10]
Time complexity: O(N+K), where N is the length of test_list2 and K is the length of test_list1 up to the Kth element.
Auxiliary space: O(N+K)
Similar Reads
Python - Accessing nth element from tuples in list
We are given tuples in list we need to access Nth elements from tuples. For example, we are having a list l = [(1, 2), (3, 4), (5, 6)] we need to access the Nth element from tuple suppose we need to access n=1 or 1st element from every tuple present inside list so that in this case the output should
2 min read
List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
Some of the list methods are mentioned in set 1 below More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentioned in its argum
4 min read
Python List insert() Method With Examples
Python List insert() method inserts an item at a specific index in a list. Example: [GFGTABS] Python # creating a list fruit = ["banana","cherry","grape"] fruit.insert(1,"apple") print(fruit) [/GFGTABS]Output['banana', 'apple', 'cherry', 'grape'] Definition an
6 min read
Python - Print list after removing element at given index
In this article, we will explore different ways to remove an element from a list at a given index and print the updated list, offering multiple approaches for achieving this. Using pop()pop() method removes the element at a specified index and returns it. [GFGTABS] Python li = [10, 20, 30, 40, 50] i
2 min read
Iterate over Two Lists with Different Lengths in Python
Iterating over two lists of different lengths is a common scenario in Python. However, we may face challenges when one list is shorter than the other. Fortunately, Python offers several methods to handle such cases, ensuring that our code is both readable and efficient. Using zip() function - Loop u
3 min read
How to Create a List of N-Lists in Python
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
Prepend Elements to Lists in Python
In Python, prepending means adding elements to the beginning of a list. We can think of it as putting something at the front of a queue. In this article, we will explore various methods to prepend elements to lists in Python. The insert() method to add an element at a specific position in a list. To
2 min read
Python | Add element at alternate position in list
Sometimes, while working with Python list, we can have a problem in which we need to add elements in list alternatively i.e at even positions and reorder the list accordingly. This has a potential application in many domains such as day-day programming and competitive programming. Let's discuss cert
2 min read
How to add Elements to a List in Python
In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method: [GFGTABS] Python a = [1, 2, 3] a.ap
2 min read
Python | Indices of Kth element value
Sometimes, while working with records, we might have a problem in which we need to find all the indices of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Let's discuss
4 min read