# How can I insert an element every $n$th position in a list?

How can I insert an element every $n$ positions in a list?

For example, inserting a zero as every 4th element to turn

{1, 2, 3, 4, 5, 6, 7}

into

{1, 2, 3, 0, 4, 5, 6, 0, 7}

Surely there must be a simpler way than

list = {1, 2, 3, 4, 5, 6, 7};
every = 4;
Insert[list, 0, List /@ Range[1, Floor[Length@list/(every - 1)]]*(every - 1)]

I'm answering my own question because I found it curious that neither Google nor Mathematica's documentation located my solution when I searched by, what were to me, the most obvious combinations of keyphrases, e.g. mathematica insert every list.

Riffle is probably an obvious thought for anyone familiar with Mathematica, but not a common term that newcomers could be expected to know. Until today, even my own idea of Riffle was that it was a "zipper" function (i.e. interleaving two lists but without an "every" option).

This is exactly one of the things Riffle does.

list = {1, 2, 3, 4, 5, 6, 7};
every = 4;
Riffle[list, 0, every]
(* {1, 2, 3, 0, 4, 5, 6, 0, 7} *)
• Insert[lst, ele, Transpose@{Range[every, Length@lst, every - 1]}] is a bit cleaner way using Insert, and Riffle is in the "see also" for Insert (I always follow those links - often a surprise or an "ah-ha!" to be found there...) – ciao Mar 26 '15 at 5:45
• Ah, I didn't see that! I'll be sure to check the "see also" more vigilantly from hereon... – Andrew Cheong Mar 26 '15 at 5:57

Riffle is surely the canonical method since version 6 but there are other approaches:

fn1[lst_, ele_, n_, m_: 1] :=
Take[
Join @@ ArrayPad[Partition[lst, n, n, 1], {0, {0, m}}, ele],
QuotientRemainder[Length @ lst, n].{n + m, 1}
]

Test:

fn1[Range@10, "x", 3]
fn1[Range@10, "x", 4, 2]
fn1[Range@10, "x", 5, 3]
{1, 2, 3, "x", 4, 5, 6, "x", 7, 8, 9, "x", 10}

{1, 2, 3, 4, "x", "x", 5, 6, 7, 8, "x", "x", 9, 10}

{1, 2, 3, 4, 5, "x", "x", "x", 6, 7, 8, 9, 10, "x", "x", "x"}

Also:

fn1[Range@10, {"a", "b"}, 3, 2]
{1, 2, 3, "a", "b", 4, 5, 6, "a", "b", 7, 8, 9, "a", "b", 10}

Related: