5
$\begingroup$

I have the following lists:

list1={1,2,3,4,5};
list2={10,20,30,40,50};

I want to combine these lists such that each element in list1 is added to every element in list2, to form list3 as

list3={1+10,1+20,1+30,1+40,1+50,2+10,2+20,2+30,2+40,2+50,....,5+10,5+20,5+30,5+40,5+50}

How can this be done efficiently?

$\endgroup$
6
$\begingroup$
Total[Tuples[{list1, list2}], {2}] (* or *)
Join @@ Outer[Plus, list1, list2]

{11, 21, 31, 41, 51, 12, 22, 32, 42, 52, 13, 23, 33, 43, 53, 14, 24, 34, 44, 54, 15, 25, 35, 45, 55}

 Tuples[Inactive[Plus][list1, list2]] (* or *)
 Join @@ Outer[Inactive[Plus], list1, list2]

{1+10, 1+20, 1+30, 1+40, 1+50, 2+10, 2+20, 2+30, 2+40, 2+50, 3+10, 3+20,3+30,3+40, 3+50, 4+10, 4+20, 4+30, 4+40, 4+50, 5+10, 5+20, 5+30, 5+40, 5+50}

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Big lesson @kglr Inactive ... never found before, thanks $\endgroup$ – Anxon Pués Jan 20 '18 at 20:40
  • $\begingroup$ @AnxonPués, it is new in version 10.0 $\endgroup$ – kglr Jan 20 '18 at 21:06
2
$\begingroup$
Plus @@@ Tuples[{list1, list2}]

or

Flatten @ Outer[Plus, list1, list2]

{11, 21, 31, 41, 51, 12, 22, 32, 42, 52, 13, 23, 33, 43, 53, 14, 24, 34, 44, 54, 15, 25, 35, 45, 55}

|improve this answer|||||
$\endgroup$
1
$\begingroup$

In case you want to have as indicated this would work

Flatten[Table[
  ToString[list1[[i]]] <> "+" <> ToString[list2[[j]]], {i, 
   Length[list1]}, {j, Length[list2]}]]
|improve this answer|||||
$\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.