Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Append List every Nth index
When you need to insert elements from one list at every Nth index position of another list, you can use enumerate() to track indices and conditionally insert elements.
Basic Example
Here's how to append a list every Nth index ?
numbers = [13, 27, 48, 12, 21, 45, 28, 19, 63]
append_list = ['P', 'Y', 'T']
N = 3
print("Original list:")
print(numbers)
print(f"Append list: {append_list}")
print(f"N = {N}")
result = []
for index, element in enumerate(numbers):
if index % N == 0:
for item in append_list:
result.append(item)
result.append(element)
print("Result:")
print(result)
Original list: [13, 27, 48, 12, 21, 45, 28, 19, 63] Append list: ['P', 'Y', 'T'] N = 3 Result: ['P', 'Y', 'T', 13, 27, 48, 'P', 'Y', 'T', 12, 21, 45, 'P', 'Y', 'T', 28, 19, 63]
How It Works
The algorithm works as follows:
-
enumerate()provides both index and element from the original list -
index % N == 0checks if the current position is divisible by N - When true, all elements from
append_listare added before the current element - The current element is always added to maintain the original sequence
Alternative Using List Comprehension
You can achieve the same result with a more compact approach ?
numbers = [13, 27, 48, 12, 21, 45, 28, 19, 63]
append_list = ['P', 'Y', 'T']
N = 3
result = []
for i, num in enumerate(numbers):
if i % N == 0:
result.extend(append_list)
result.append(num)
print("Result using extend():")
print(result)
Result using extend(): ['P', 'Y', 'T', 13, 27, 48, 'P', 'Y', 'T', 12, 21, 45, 'P', 'Y', 'T', 28, 19, 63]
Different N Values
Here's how the output changes with different N values ?
numbers = [1, 2, 3, 4, 5, 6]
append_list = ['X']
for N in [1, 2, 3]:
result = []
for i, num in enumerate(numbers):
if i % N == 0:
result.extend(append_list)
result.append(num)
print(f"N={N}: {result}")
N=1: ['X', 1, 'X', 2, 'X', 3, 'X', 4, 'X', 5, 'X', 6] N=2: ['X', 1, 2, 'X', 3, 4, 'X', 5, 6] N=3: ['X', 1, 2, 3, 'X', 4, 5, 6]
Conclusion
Use enumerate() with modulo operator to insert elements at every Nth index. The extend() method provides a cleaner way to add multiple elements at once compared to nested loops.
Advertisements
