How to repeat each element in a list and the whole list as well?

Repeated list:

SeedRandom[666];
list = RandomInteger[{1, 100000}, 1000000];
n = 3;

akglr = Join @@ {list}[[ConstantArray[1, n]]]; // RepeatedTiming // First
aCE = PadRight[list, n Length[list], list]; // RepeatedTiming // First
aCarl = Flatten[Outer[Times, ConstantArray[1, n], list]]; // RepeatedTiming // First
aMajis = Flatten@Developer`ToPackedArray[Table[list, n]]; // RepeatedTiming // First
aHenrik = Flatten[ConstantArray[list, n]]; // RepeatedTiming // First
aMajis0 = Flatten@Table[list, n]; // RepeatedTiming // First

aMajis0 == aMajis == aCE == aCarl == aHenrik == akglr1 == akglr2

0.0050

0.0059

0.0087

0.011

0.010

0.21

Duplicating list elements:

bkglr = Flatten@Transpose[{list}[[ConstantArray[1, 3]]]]; // RepeatedTiming // First
bHenrik = Flatten[Transpose[ConstantArray[list, 3]]]; // RepeatedTiming // First
bCarl = Flatten@Outer[Times, list, ConstantArray[1, 3]]; // RepeatedTiming // First
bJason = Fold[Riffle[#1, list, {#2, -1, #2}] &, list, Range[2, n]]; // RepeatedTiming // First

bkglr == bHenrik == bCarl == bJason

0.016

0.016

0.017

0.022

True

Tests ran on a Intel 4980HQ, 16 GB 1600 MHz DDR3L SDRAM.


Here's my suggestion:

list = {1, 2, 3, 4};
repeat[list_, n_] := PadRight[list, n Length[list], list]
repeat[list, 3]

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

repeat2[list_, n_] := Sequence @@ ConstantArray[#, n] & /@ list
repeat2[list, 3]

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

repeat solves the first question, and repeat2 solves the second question. Performance-wise repeat is quite a bit slower than Flatten@ConstantArray[list, n], as suggested by Henrik. repeat2 I think should be rather fast. It also has the advantage that I don't apply Flatten or do any such thing at the end, so it will work even if the list elements are themselves lists.


f1 = Join @@ {#}[[ConstantArray[1, #2]]] &;
f1[Range[4], 3]

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

f2 = Flatten@Transpose[{#}[[ConstantArray[1, #2]]]] &;
f2[Range[4], 3]

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