# Combine each element with all the others in sublists

Suppose that I have a list of numbers

list = {{{1, 0}, {-1, 1}, {0, -1}}, {{-1, 0, 1}, {-1, 1, -1}, {-1, -1, 0}, {1, 1, 0}, {1, -1, 1}, {1, 0, -1}}}


I would like to Join each element of the first sublist with each element of the second list. In principle I would like to do it recursively, so the list might have also multiple sublists. The final result should be

final = {
{{1,0,-1, 0, 1}, {1,0,-1, 1, -1}, {1,0,-1, -1, 0}, {1,0,1, 1, 0}, {1,0,1, -1, 1}, {1,0,1, 0, -1}}, (*first union*)
{{-1, 1,-1, 0, 1}, {-1, 1,-1, 1, -1}, {-1, 1,-1, -1, 0}, {-1, 1,1, 1, 0}, {-1, 1,1, -1, 1}, {-1, 1,1, 0, -1}},  (*second union*)
{{0, -1,-1, 0, 1}, {0, -1,-1, 1, -1}, {0, -1,-1, -1, 0}, {0, -1,1, 1, 0}, {0, -1,1, -1, 1}, {0, -1,1, 0, -1}}  (*third union*)
}


In case I had three sublist, I need to create all possible combination of these final result (which can be flattened) with the element of the third sublist. So I was thinking of sum recursive solution that applies to each pair of the array.

What is the correct way of doing it in Mathematica?

EDIT with example:

Just to give you a case with three vectors: list ={{{1}},{{1,0},{-1,1},{0,-1}},{{-1,0,1},{-1,1,-1},{-1,-1,0},{1,1,0},{1,-1,1},{1,0,-1}}},

temp={};
Do[
temp=AppendTo[temp,Join[list[[1,i]],list[[2,j]],list[[3,k]]]];
,{i,1,Length[list[[1]]]},{j,1,Length[list[[2]]]},{k,1,Length[list[[3]]]}]


and it does the job, but of course, I could have a list with more than three sublists, and for sure there is a better way than a Do loop. But now it is clear what I want, I guess.

You can get the desired ouput like so:

Join@Outer[Join, list[[1]], list[[2]], 1]


and check

final - Join@Outer[Join, list[[1]], list[[2]], 1]


• Perfect, I can use your function Join@Outer[Join, Evaluate @@ list, 1] for a generic long list and it works. I then flatten as much time as I need. Thanks! Commented Mar 22, 2022 at 21:27
• @AlessandroMininno hi. Yes, indeed this is the idea. You can pass as many lists as you want. You might want to have a look at Outer, but it seems you got the general picture
– bmf
Commented Mar 22, 2022 at 21:28

1st solution

{x, y} = list;

la = (n |-> Join[x[[n]], #] & /@ y) /@ Range[Length @ x];


2nd solution

lb =
GatherBy[
Cases[Subsets[Join @@ list, {2}], x : {{_, _}, {_, _, _}} :> Flatten[x]],
First];


Test

la == lb == final


True