# Repeating a list k times [duplicate]

I have a list, say $$\{1,2,3,4\}$$ and I would like to repeat this list k times to obtain a list of $$4k$$ elements that looks like $$\{1,2,3,4,1,2,..,1,2,3,4\}$$.

I was hoping something like li * k would do this but unfortunately that's pointwise multiplication. What's the right operator that would do something like this for me?

list = {1, 2, 3, 4};

a = Flatten @ Table[list, 4]

{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}

b = Round @ Flatten @ ReplicateLayer[4, 1] @ list

{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}

c = Round @ Flatten @ ReplicateLayer[4, 2] @ list

{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}

ReplicateLayer packs, Table doesn't:

DeveloperPackedArrayQ /@ {a, b, c}

{False, True, True}

what-is-a-mathematica-packed-array

One can easily chain layers:

rep = Round @* ReplicateLayer[2,1] @* Flatten @* ReplicateLayer[2, 1];

rep @ list // MatrixForm

### ConstantArray + Splice

ClearAll[Star]

Star[l_, k_] := ConstantArray[Splice @ l, k]

{1, 2, 3, 4}⋆3
{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}

Use Table instead of ConstantArray to get the same result.

ClearAll[Diamond]

Diamond[l_List, k_Integer] := PadRight[l, k Length@l, l]

{1, 2, 3, 4}⋄3
{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}

Note: You can use any of the Operators without Built-in Meanings instead of \[Star] and \[Diamond].

Note: Although still undocumented, PadRight[l, k Length@l, "Periodic"] also works.

• How does one discover hidden "options" like "Periodic"? Also, hopefully no one ever needs to use "Periodic" as their padding :) . I usually use the list itself as padding PadRight[list, length, list]. Commented Nov 12, 2023 at 17:37
• @lericr, discovered "Periodic" in the third argument of PadRight/PadLeft by the method of wishful thinking + luck:) I agree PadRight[list, length, list] is woker.
– kglr
Commented Nov 12, 2023 at 17:48
• Excellent! Thanks! Commented Nov 12, 2023 at 17:52

Maybe we can get 10 ways to do this. Just to the add to the list of fun ways to do this using fun function names:

𒓬[l0_, k_] := Nest[Join[#, l0] &, {}, k]

𒓬[Range@4, 3]

(*{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}*)
SubstitutionSystem[MapApply[Rule]@Partition[Range[#1],
2,1,1],1,(#1 #2)-1]&[4,3]//Flatten

(* {1,2,3,4,1,2,3,4,1,2,3,4} *)

SubstitutionSystem[MapApply[Rule]@Partition[Range[#1],
2,1,1],1,(#1 #2)-1]&[10,3]//Flatten

(* {1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10} *)

Using ConstantArray and Cases:

f[lst_, k_] := Cases[ConstantArray[lst, k], x_ :> Sequence @@ x]

f[list, 4]

(*{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}*)
list = {1, 2, 3, 4};
k = 4;
ArrayReshape[list, {Length[list] k}, list]

(* {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4} *)

Flatten@Array[list &, k]

(* {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4} *)
$$$$