# Generating repeated elements in a list [closed]

Is there a function in mathematica that allows you to generate repeated elements inline within a list. For example, let's say you provided this as input text:

{1, 2, 3, 4, Repeat[5,3], 6, 7}

Then I would want Mathematica to provide the output as

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

I know there already exists something similar ConstantArray and Nest but they cannot be used in the manner described above, for doing so leads to a nested list:

{1, 2, 3, 4, ConstantArray[5, 3], 6}

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

which I would then have to Flatten, a clunky solution that is less elegant than ideal.

Since I am reasonably sure that no native function exists, how would you go about building one?

• You are looking for Sequence! Alternatively, if you really want to build it yourself, Replace with a suitable pattern will do the job. – Oleksandr R. Sep 1 '15 at 0:28
• Sequence@ConstantArray... – ciao Sep 1 '15 at 0:28
• @ciao Sequence@@ConstantArray[..] -- you have a typo. – Oleksandr R. Sep 1 '15 at 0:30
• @OleksandrR. Can you show a usage example? I don't see how to use sequence when trying to splice in repeated copies of an element. – 1110101001 Sep 1 '15 at 0:32
• Of course. {1, Sequence @@ ConstantArray[5, 3], 2} gives {1, 5, 5, 5, 2}. Define repeat[what_, times_] := Sequence @@ ConstantArray[what, times] and you can write {1, 2, 3, 4, repeat[5,3], 6, 7}, just like in the question. – Oleksandr R. Sep 1 '15 at 0:32

## 1 Answer

You can write your own repeat function like this:

repeat[m_, n_Integer?Positive] := Sequence @@ ConstantArray[m, n]


Then

{1, 2, 3, 4, repeat[5, 3], 6, 7}


evaluates to

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


The first argument can be anything.

{1, 2, 3, 4, repeat["anything", 2], 6, 7}

{1, 2, 3, 4, "anything", "anything", 6, 7}

• I told my doctor, "When I do this it hurts". He told me, "Then don't do that". :P – m_goldberg Sep 1 '15 at 1:30