Related Articles

Related Articles

Python – Append List every Nth index
  • Last Updated : 11 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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]

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :