Open In App

Python | Selective Merge list every Nth position

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can come into a problem in which we need to perform merging in list. A simple merge of list is easier to perform. But sometimes, we need to handle variations in merge. One such can be merge one list with other at every Nth element. This particular problem can be faced in day-day programming and competitive programming. Let’s discuss certain way in which this task can be performed. 

Method : Using loop + extend() + iter() + next() In this method, we use a brute force approach to tackle this problem. In this we convert a larger list into an iterator and then access it’s element using next(). The whole idea behind this is faster access of elements. Smaller list is checked for every N element. 

Python3




# Python3 code to demonstrate working of
# Selective Merge list every Nth position
# using loop + extend() + iter() + next()
 
# initialize lists
test_list1 = [1, 4, 9, 10, 19, 65, 78, 23, 78]
test_list2 = [8, 14, 50]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Selective Merge list every Nth position
# using loop + extend() + iter() + next()
N = 3
temp_iter = iter(test_list1)
res = []
for ele in test_list2:
    res.extend([next(temp_iter) for _ in range(N - 1)])
    res.append(ele)
res.extend(temp_iter)
 
# printing result
print("The List after merge is : " + str(res))


Output : 

The original list 1 is : [1, 4, 9, 10, 19, 65, 78, 23, 78]
The original list 2 is : [8, 14, 50]
The List after merge is : [1, 4, 8, 9, 10, 14, 19, 65, 50, 78, 23, 78]

Time Complexity: O(m*n) where m and n are the number of elements in the list “test_list 1 and test_list2 respectively”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method#2 : Using while loop

To selectively merge two lists in Python, you can use a loop to iterate over one of the lists, and insert the elements of the other list at every Nth position using slicing

Python3




list1 = [1, 4, 9, 10, 19, 65, 78, 23, 78]
list2 = [8, 14, 50]
N = 3  # merge every 3rd position
 
i = N-1  # initialize i to the (N-1)th index of list1
j = 0   # initialize j to the first index of list2
while j < len(list2):
    # if i goes beyond the last index of list1, append the remaining elements of list2 to list1
    if i >= len(list1):
        list1.extend(list2[j:])
        break
    # insert the current element of list2 at the ith index of list1
    list1.insert(i, list2[j])
    # increment i by N to move to the next merge position in list1
    i += N
    # increment j by 1 to move to the next element in list2
    j += 1
 
print("The List after merge is :", list1)


Output

The List after merge is : [1, 4, 8, 9, 10, 14, 19, 65, 50, 78, 23, 78]

Time complexity: O(mn)
Auxiliary Space: O(1)

Method#3 :numpy:

Algorithm:

1. Convert list1 to a numpy array.
2.Create an array of indices to insert the elements of list2, using numpy’s arange function.
3.Use numpy’s insert function to insert the elements of list2 into list1 at the specified indices.
4.Print the merged list.

Python3




import numpy as np
 
list1 = [1, 4, 9, 10, 19, 65, 78, 23, 78]
list2 = [8, 14, 50]
N = 3
 
# Convert list1 to a numpy array
merged_list = np.array(list1)
 
# Create array of indices to insert the elements of list2
indices = np.arange(N-1, len(list1), N)
 
# Insert elements of list2 into list1 at the specified indices
merged_list = np.insert(merged_list, indices, list2)
 
print("The List after merge is :", merged_list)
 
#This  code is contributed by Jyothi pinjala.


Output:

The List after merge is : [ 1  4  8  9 10 19 14 65 78 23 50 78]

Time Complexity: O(n)

Converting list1 to a numpy array takes O(n).
Creating the array of indices takes O(n/N) = O(n).
Inserting elements of list2 into list1 at the specified indices takes O(n).
Overall time complexity is O(n).
Space Complexity: O(n)

A numpy array of size n is created to hold the merged list.
Overall space complexity is O(n).

Method 4: Using list comprehension and slicing:

This method works by dividing list1 into sublists of length N, and then concatenating each sublist with the corresponding element of list2 using list comprehension. If i goes beyond the length of list1, it will concatenate the remaining elements of list2 to the last sublist of list1. Finally, the resulting merged sublists are flattened into a single list using another list comprehension.

Python3




# define the input lists and the merge interval
list1 = [1, 4, 9, 10, 19, 65, 78, 23, 78]
list2 = [8, 14, 50]
N = 3
 
# create a list of merged sublists
# each merged sublist consists of the next N elements from list1 and the next element from list2
# if the end of list1 is reached, the remaining elements from list2 are appended to the last sublist
merged = [list1[i:i+N] + list2[i:i+1] if i < len(list1) else list1[i:] + list2[i:] for i in range(0, len(list1), N)]
 
# flatten the list of merged sublists into a single list
result = [x for sublist in merged for x in sublist]
 
# print the resulting list
print("The List after merge is: ", result)


Output

The List after merge is:  [1, 4, 9, 8, 10, 19, 65, 78, 23, 78]

Time complexity: O(N), as it requires iterating over list1 once to create the merged sublists. 
Auxiliary space: O(N), as it creates a new list for each merged sublist.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads