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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

24 lines
Python 3.9+
def 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

stdout
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

  1. 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 [])]`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.