# List of the combinations of more lists via permutations

I would like to generate a list of all the possible combinations of two lists. As for instance, given L=3;

list={0,1,2};


I would like to obtain the list {{0,0,0},{0,0,1},{0,0,2},{0,1,0},{0,2,0},{1,0,0},{2,0,0}}

I did it with the code:

f[d_, L_] := Module[{l, st},
l = Join[{d}, Table[0, {j, L - 1}]];
st = {};
AppendTo[st, Permutations@l];
Return[First@st];
];

d = 2;
L = 3;
Flatten[Join[Table[f[j, L], {j, 0, d}]], 1]


Is there a better way to do by combining lists?

• What two lists?
– Kuba
Jul 3, 2017 at 12:45
• Related: (41614), (82801), (138472) Jul 3, 2017 at 13:18

Starting over I just realized that for the example given we can do this simply with KroneckerProduct:

f2[d_, L_] :=
Range[d] ~KroneckerProduct~ IdentityMatrix[L] // Prepend[#, 0*First@#] &

f2[2, 3]


(* {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {2, 0, 0}, {0, 2, 0}, {0, 0, 2}} *)

f2[86, 99] // Length // RepeatedTiming


(* {0.00445, 8515} *)

If you will accept your output in the form of a SparseArray this can be made more than an order of magnitude faster:

f3[d_, L_] :=
Range[d] ~KroneckerProduct~ IdentityMatrix[L, SparseArray] // Prepend[#, 0*First@#] &

f3[86, 99] // Length // RepeatedTiming


(* {0.000288, 8515} *)

Compare the performance of kglr's method, e.g.:

fx[d_, L_] :=
With[{list = Range[0, d], list2 = ConstantArray[0, L - 1]},
Sort[Join @@ (Permutations[Join[list2, {#}]] & /@ list)]
]

fx[86, 99] // Length // RepeatedTiming


(* {0.05107, 8515} *)

• Thank you so much...it works perfectly! Jul 3, 2017 at 14:06
• I changed the Prepend part to // Prepend[ConstantArray[0, {L}]]...it seems it goes just a bit faster Jul 3, 2017 at 14:15
• @Galuoises You're welcome. By the way if order matters and you want a different one try KroneckerProduct[IdentityMatrix[L], Range[d]]\[Transpose] // Prepend[#, ConstantArray[0, L]] & Jul 3, 2017 at 14:46
list = {0, 1, 2};
list2 = {0, 0};
Sort[Join @@ (Permutations[Join[list2, {#}]] & /@ list)]


{{0, 0, 0}, {0, 0, 1}, {0, 0, 2}, {0, 1, 0}, {0, 2, 0}, {1, 0, 0}, {2, 0, 0}}

Permutations[{0, 0, #}, {3}] & /@ Range[0, 2] // Flatten[#, 1] &


Permutations /@ IntegerDigits[Range[0, 2], 2 + 1, 3] // Join @@ # &

• No need for , {3} in Permutations` that I can see, as that is implicit I think? Jul 4, 2017 at 1:28