# Repeat elements in list, but the number of times each element is repeated is provided by a separate list

I'm trying to repeat each element of a list x number of times, where x is the corresponding element of the same position in another list.

For example, I have list A = {1,2,3,4} and another list B = {3,1,4,2} and I'm trying to get C = {1,1,1,2,3,3,3,3,4,4}.

How do I get C from A and B?

• What have you tried? – Edmund Sep 18 at 16:23

Join @@ MapThread[Table, {A,B}]


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

Join @@ Table @@@ Transpose @ {A,B}


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

Join @@ MapThread[ConstantArray, {A, B}]


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

Also

InternalRepetitionFromMultiplicity @ Transpose[{A, B}]


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

kglr's proposals are nice, and the last (undocumented) one is very nice. As a variation, here is a solution using Inner[] + Flatten[]:

Flatten[Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, List]]
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}


As kglr notes, a shorter version is

Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, Join]


or in version 10 and later,

Inner[Table, {1, 2, 3, 4}, {3, 1, 4, 2}, Join]

• shorter Inner[ConstantArray, {1, 2, 3, 4}, {3, 1, 4, 2}, Join] (+1) – kglr Sep 19 at 14:10
• Indeed, thank you! – J. M. will be back soon Sep 21 at 5:19
a = {1, 2, 3, 4};

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

c = Flatten[ConstantArray[#[], #[]] & /@
Transpose[{a, b}]]

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


or using Table

c = Flatten[Table[#[], {#[]}] & /@
Transpose[{a, b}]]

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


Another way of approaching this is to define a function that carries out the basic task. In this case, to repeat the x element y times.

f[x_, y_] := ConstantArray[x, y]; SetAttributes[f, Listable]


Making this function Listable allows very simple calling method:

f[a, b] // Flatten
{1, 1, 1, 2, 3, 3, 3, 3, 4, 4}

a = {1, 2, 3, 4};
b = {3, 1, 4, 2};

Flatten[Table[a[[n]], {n, Length[a]}, {b[[n]]}]]
(* or *)
Flatten[Table[Table[a[[n]], {b[[n]]}], {n, Length[a]}]]


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

Flatten[Table[ConstantArray[a[[n]], b[[n]]], {n, Length[a]}]]
`

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