Insert an Element Every n Positions in Python
Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.
Python code
24 linesdef insert_every_n(seq, element, n, position="after"):
"""Insert an element before or after every n-th position in a list.
Args:
seq: Input list
element: Element to insert
n: Insert every n positions (n > 0)
position: 'before' or 'after' (default: 'after')
Returns:
New list with the element inserted
"""
if n <= 0:
raise ValueError("n must be positive")
result = list(seq)
insert_at = n if position == "after" else n - 1
for i in range(insert_at, len(result), n + 1):
result.insert(i, element)
return result
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Original: ", nums)
print("After n=3:", insert_every_n(nums, "X", 3, "after"))
print("Before n=3:", insert_every_n(nums, "Y", 3, "before"))
Output
Original: [1, 2, 3, 4, 5, 6, 7, 8, 9]
After n=3: [1, 2, 3, 'X', 4, 5, 6, 'X', 7, 8, 9, 'X']
Before n=3: [1, 2, 'Y', 3, 4, 5, 'Y', 6, 7, 8, 'Y', 9]
How it works
The function works by converting the input sequence into a list and then iterating backward-friendly forward indices based on the position parameter. Using result.insert(i, element) shifts subsequent elements automatically. The loop step is n + 1 because each insertion increases the list length by 1, so the next insertion point must be offset accordingly. By computing insert_at once before the loop, we correctly handle both 'before' and 'after' cases without special-casing inside the iteration.
Common mistakes
- Using `n` as the loop step instead of `n + 1`, causing insertions to drift as the list grows.
- Modifying the original list in place instead of creating a copy with `list(seq)`.
- Forgetting to validate `n > 0`, which can cause infinite loops or index errors.
Variations
- Use a list comprehension with slicing to create the result in one pass: `[item for i, item in enumerate(seq) for _ in ([element] if (i + 1) % n == 0 and position == 'after' else [])]`
- For large lists, consider building the output by joining chunks with `itertools.islice` for better performance.
Real-world use cases
- Adding separators or markers to serialized data streams every fixed number of records.
- Inserting pagination delimiters into a flat list to group items into chunks of n.
- Injecting audit placeholders into a data pipeline at regular intervals for monitoring.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.