Python – Append List every Nth index

PythonServer Side ProgrammingProgramming

When it is required to append list every ‘N’th index, a simple iteration and the ‘enumerate’ attribute are used.

Example

Below is a demonstration of the same −

my_list = [13, 27, 48, 12, 21, 45, 28, 19, 63]

print("The list is :")
print(my_list)

append_list = ['P', 'Y', 'T']

N = 3
print("The value of N is ")
print(N)

my_result = []

for index, element in enumerate(my_list):
   if index % N == 0:
      for element_in in append_list:
         my_result.append(element_in)
   my_result.append(element)

print("The result is :")
print(my_result)

Output

The list is :
[13, 27, 48, 12, 21, 45, 28, 19, 63]
The value of N is
3
The result is :
['P', 'Y', 'T', 13, 27, 48, 'P', 'Y', 'T', 12, 21, 45, 'P', 'Y', 'T', 28, 19, 63]

Explanation

  • A list is defined and displayed on the console.

  • Another integer list is defined.

  • The value for N is defined and displayed on the console.

  • An empty list is created.

  • The list is iterated over using ‘enumerate’, and every element is divided by N and its remainder is compared to 0.

  • If it is 0, the element is again checked if it is present in the integer list.

  • If yes, it is appended to the empty list.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 09:13:57
Advertisements