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
# Python3 code to demonstrate working of
# Insert Nth element to Kth element in other list
# Using pop() + index() + insert()
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing N
N = 5
# initializing K
K = 3
# Using pop() + index() + insert()
# Insert Nth element to Kth element in other list
res = test_list1.insert(K, test_list2.pop(N))
# Printing result
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
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# initializing N and K
N = 5
K = 3
# insert Nth element of test_list2 to Kth position of test_list1
res = test_list1[:K] + [test_list2[N]] + test_list1[K:]
# Printing result
print("The list 1 after insert is : " + str(res))
print("The list 2 after remove is : " + str(test_list2[:N] + test_list2[N+1:]))
OutputThe 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
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# initializing N and K
N = 5
K = 3
# using list comprehension
res = [test_list1[i] for i in range(
K)] + [test_list2[N]] + [test_list1[i] for i in range(K, len(test_list1))]
# Printing result
print("The list 1 after insert is : " + str(res))
print("The list 2 after remove is : " + str(test_list2[:N] + test_list2[N+1:]))
OutputThe 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):
# base case
if N == 0:
return [test_list2[0]] + test_list1
# recursive case
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)
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# initializing N and K
N = 5
K = 3
res = insert_remove(test_list1, test_list2, N, K)
# Printing result
print("The list 1 after insert is : " + str(res))
print("The list 2 after remove is : " + str(test_list2[:N] + test_list2[N+1:]))
OutputThe 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
# Python3 code to demonstrate working of
# Insert Nth element to Kth element in other list
# Using extend()
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing N
N = 5
# initializing K
K = 3
# Using extend() method
# Insert Nth element to Kth element in other list
test_list1[K:K] = [test_list2.pop(N)]
# Printing result
print("The list 1 after insert is : " + str(test_list1))
print("The list 2 after remove is : " + str(test_list2))
OutputThe 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
# importing itertools module
import itertools
# initializing lists
test_list1 = [4, 5, 6, 7, 3, 8]
test_list2 = [7, 6, 3, 8, 10, 12]
# initializing N and K
N = 5
K = 3
# using the itertools module
res = list(itertools.chain(test_list1[:K], test_list2[K:N], test_list2[N:N+1], test_list1[K:]))
# Printing result
print("The list 1 after insert is : " + str(res))
print("The list 2 after remove is : " + str(test_list2[:N] + test_list2[N+1:]))
OutputThe 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 List insert() Method With Examples Python List insert() method inserts an item at a specific index in a list.Example:Python# creating a list fruit = ["banana","cherry","grape"] fruit.insert(1,"apple") print(fruit)Output['banana', 'apple', 'cherry', 'grape'] Definition and Use of List insert() MethodList insert() method in Python is v
5 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
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
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
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:Pythona = [1, 2, 3] a.append(4) prin
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
Iterate over a list in Python Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
3 min read
Python - Append List every Nth index Given 2 list, append list to the original list every nth index. Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = ['G', 'F', 'G'], N = 3 Output : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2
5 min read
Python - Insert the string at the beginning of all items in a list In Python, modifying list elements by adding a specific string to the beginning of each item is a common and useful task. By iterating through the list and appending the desired string to each element, we can create a new list with the updated values.Using map()map() function allows us to apply a sp
3 min read
Python Indexerror: list assignment index out of range Solution In Python, the IndexError: list assignment index out of range occurs when we try to assign a value to an index that exceeds the current bounds of the list. Since lists are dynamically sized and zero-indexed, it's important to ensure the index exists within the list's range before modifying it. Under
2 min read