Python - Append List every Nth index
Last Updated :
21 Apr, 2023
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, 1, 5, 8, 9], app_list = ['G', 'F', 'G'], N = 4
Output : ['G', 'F', 'G', 3, 7, 8, 2, 'G', 'F', 'G', 1, 5, 8, 9 'G', 'F', 'G']
Explanation : List is added after every 4th element.
Method #1 : Using loop
This is brute way to solve this problem, in this, every nth index, inner loop is used to append all other list elements.
Python3
# Python3 code to demonstrate working of
# Append List every Nth index
# Using loop
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
res = []
for idx, ele in enumerate(test_list):
# if index multiple of N
if idx % N == 0:
for ele_in in app_list:
res.append(ele_in)
res.append(ele)
# printing result
print("The appended list : " + str(res))
Output:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3] The appended list : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8, 9, 3]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using extend()
Another way to solve this problem. In this, we use extend to get all the elements in every Nth index, rather than inner list.
Python3
# Python3 code to demonstrate working of
# Append List every Nth index
# Using extend()
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
res = []
for idx, ele in enumerate(test_list):
# if index multiple of N
if idx % N == 0:
# extend to append all elements
res.extend(app_list)
res.append(ele)
# printing result
print("The appended list : " + str(res))
Output:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3] The appended list : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8, 9, 3]
Time Complexity : O(n)
Auxiliary Space : O(n), where n is length of test_list.
Method#3: Using Recursive method.
This implementation uses recursion to append the app_list every Nth index of the test_list. The base case is when i is greater than or equal to the length of test_list. If i is a multiple of N, it concatenates app_list, the current element of test_list, and the result of the recursive call with i incremented by 1. Otherwise, it concatenates only the current element of test_list and the result of the recursive call with i incremented by 1. The final result is returned as a list.
Python3
def append_list_n_recursive(test_list, app_list, N, i=0):
if i >= len(test_list):
return []
elif i % N == 0:
return app_list + [test_list[i]] + append_list_n_recursive(test_list, app_list, N, i+1)
else:
return [test_list[i]] + append_list_n_recursive(test_list, app_list, N, i+1)
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
# printing result
print("The appended list : " + str(append_list_n_recursive(test_list, app_list, N)))
OutputThe original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]
The appended list : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8, 9, 3]
The time complexity of the recursive implementation of append_list_n_recursive function is O(n), where n is the length of the test_list.
The space complexity of the recursive implementation is also O(n), where n is the length of the test_list. This is because at any point during the recursion, there will be at most n recursive calls on the call stack, each of which stores a constant amount of information, including the current index, the app_list, and the res list.
Method #4: Using List Comprehension
- Initialize an empty list result_list to store the final appended list.
- Loop through the range of 0 to the length of the test_list with a step of N.
- Inside the loop, concatenate the sublist of test_list from the current index to the next N elements with the app_list.
- Extend the concatenated list to the result_list.
- Finally, concatenate the remaining elements of test_list that are not appended with the app_list.
- Return the result_list.
Python3
def append_list_n(test_list, app_list, N):
result_list = []
for i in range(0, len(test_list), N):
result_list.extend(app_list + test_list[i:i+N])
result_list += test_list[len(result_list):]
return result_list
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
# printing result
print("The appended list : " + str(append_list_n(test_list, app_list, N)))
OutputThe original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]
The appended list : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8, 9, 3]
Time complexity: The loop runs for len(test_list) // N times, so the time complexity is O(len(test_list) // N).
The space complexity is O(len(test_list)) as the final appended list can have all the elements of test_list along with the app_list.
Similar Reads
Appending to 2D List in Python A 2D list in Python is a list of lists where each sublist can hold elements. Appending to a 2D list involves adding either a new sublist or elements to an existing sublist. The simplest way to append a new sublist to a 2D list is by using the append() method.Pythona = [[1, 2], [3, 4]] # Append a new
2 min read
Extending a list in Python In Python, a list is one of the most widely used data structures for storing multiple items in a single variable. Often, we need to extend a list by adding one or more elements, either from another list or other iterable objects. Python provides several ways to achieve this. In this article, we will
2 min read
Perform Append at Beginning of List - Python The task of appending an element to the beginning of a list involves adding a new item at the start of an existing list, shifting the other elements to the right. For example, if we have a list [1, 2, 3, 4] and we want to append the value 0 at the beginning, the resulting list would be [0, 1, 2, 3,
4 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.Pythonli = [10, 20, 30, 40, 50] index = 2 li.p
2 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 | Pandas Index.insert() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.insert() function make new Index inserting new item at location. This fun
2 min read