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
Python | Pandas Index.append()
Python is an excellent language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas are one of those packages, making importing and analyzing data much easier. Pandas Index.append() The function is used to append a single or a collection of indices
2 min read
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
Python - Change List Item
Lists in Python are mutable meaning their items can be changed after the list is created. Modifying elements in a list is a common task, whether we're replacing an item at a specific index, updating multiple items at once, or using conditions to modify certain elements. This article explores the dif
3 min read
Difference Between '+' and 'append' in Python
+ Operator creates a new sequence by concatenating two existing sequences and .append() method (available for lists) modifies the existing list in place by adding one item at the end. In this article we are going to compare '+' operator and append in Python.+ Operator in Python+ operator is typicall
3 min read
Print lists in Python
Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods.The simplest way of printing a list is directly with the print() function:Pyth
3 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
Index of Non-Zero Elements in Python list
We are given a list we need to find all indexes of Non-Zero elements. For example, a = [0, 3, 0, 5, 8, 0, 2] we need to return all indexes of non-zero elements so that output should be [1, 3, 4, 6].Using List ComprehensionList comprehension can be used to find the indices of non-zero elements by ite
2 min read
Get Index of Multiple List Elements in Python
In Python, retrieving the indices of specific elements in a list is a common task that programmers often encounter. There are several methods to achieve this, each with its own advantages and use cases. In this article, we will explore some different approaches to get the index of multiple list elem
3 min read