3
$\begingroup$

I have two list to begin with.

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

I want to obtain the following output (order unimportant):

{11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43}

I can obtain it via "Table, For, Do" etc. command but I am looking for a concise code to achieve such an output?

$\endgroup$

6 Answers 6

4
$\begingroup$
Outer[Plus, list2, list1] // Flatten

enter image description here

$\endgroup$
4
$\begingroup$

A variation of Coolwater's answer:

Tuples @ Unevaluated[{10, 20, 30, 40} + {1,2,3}]

{11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43}

$\endgroup$
3
$\begingroup$
Total[Tuples[{list2, list1}], {2}]
(* {11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43} *)
$\endgroup$
2
$\begingroup$
list1+#&/@list2//Flatten

(*{11,12,13,21,22,23,31,32,33,41,42,43}*)
$\endgroup$
2
$\begingroup$

Using Thread: (and letting it morph into MapThread)

Sequence @@@ (Thread[# + list1] & /@ list2)

Sequence @@@ (Map[Thread[# + list1] &, list2])

Sequence @@@ 
 MapThread[Plus, {list2, ConstantArray[list1, Length@list2]}]

Result:

{11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43}

$\endgroup$
2
$\begingroup$
l1 = {1, 2, 3};
l2 = {10, 20, 30, 40};

Using SubsetMap:

f = Table[#, Length@l1 + 1] + Range@Length@# &;

Flatten@Thread@Most@SubsetMap[f, #, All] &@l2

(*{11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43}*)

Another very nice solution (Thanks to @Syed!) is the following:

Flatten@Thread[# + l2 & /@ l1]

(*{11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43}*)
$\endgroup$
2
  • 2
    $\begingroup$ simpler: Flatten@Thread[# + l2 & /@ l1]. I am trying to say that SubsetMap[...,All] implies that Map can be used instead. $\endgroup$
    – Syed
    Jan 31 at 4:44
  • $\begingroup$ Clever solution, Syed! :-) $\endgroup$ Jan 31 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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