3
$\begingroup$

I want to combine two list in the following way without using Table or any loop structure.

genList[n_] := Table[RandomInteger[{1, 10}, 4], n]  (* list generating function*)

The two lists that needs to be combined are:-

list1 = genList[3]
list2 = genList[4]

What I want to achieve is as follows:-

Partition[
          Flatten[
                 Table[{list1[[i]], list2[[j]]}, {i, 1 
                 Length[list1]},{j,1 Length[list2]}]
                 ]
       ,8]

So I simply need to enumerate each of the elements of list 1 combined with all of the elements of list 2.

What would be an efficient way of doing this with large lists?

Let's say with Length[list1] = 100 and Length[list2] = 200.

Also Length[list2] > Length[list1]

$\endgroup$
3
$\begingroup$
Join @@@ Tuples[{list1, list2}] (* or *)
Flatten /@ Tuples[{list1, list2}] (* or *)
Join @@ Outer[Join, list1, list2, 1]

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

$\endgroup$
3
$\begingroup$

This is a variant of kglr's approach that employs ArrayFlatten instead of mapping Flatten. Notice also that I changed genList so that it produces packed arrays; this is crucial for performance.

genList[n_] := RandomInteger[{1, 10}, {n, 4}];
m = 100;
n = 100;
list1 = genList[m];
list2 = genList[n];

a = Partition[Flatten[Table[{list1[[i]], list2[[j]]}, {i, 1 Length[list1]}, {j, 1 Length[list2]}]], 8]; // RepeatedTiming // First
b = Flatten /@ Tuples[{list1, list2}]; // RepeatedTiming // First
c = ArrayReshape[
     Tuples[{list1, list2}],
     {Length[list1] Length[list2], Dimensions[list1][[2]] + Dimensions[list2][[2]]}
     ]; // RepeatedTiming // First
a == b == c

0.026

0.0012

0.000095

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.