I have 2 lists. For example,

list1 = {{a,b}, {c, d}, {e, f}, {g, h}}

list2 = {{1}, {2}, {3}, {4}}

I want to merge them such that I get the result:

list3 = {{1,a,b}, {2,c, d}, {3,e, f}, {4,g, h}}

and the method generalizes to a large number of sublists.

How can one write a loop to execute this sequence of operations?


closed as off-topic by Mr.Wizard Aug 26 '16 at 1:38

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Mr.Wizard
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ Flatten /@ Transpose[{list2, list1}] good enough? $\endgroup$ – BlacKow Jul 26 '16 at 16:11
  • 6
    $\begingroup$ @BlacKow no, Join[list2, list1, 2] :) $\endgroup$ – Kuba Jul 26 '16 at 16:11
  • 2
    $\begingroup$ I would avoid looking for a loop to achieve this sort of stuff! There is always a better way in Mathematica. $\endgroup$ – user6014 Jul 26 '16 at 16:12
  • $\begingroup$ related: 113630 together with topics linked there. $\endgroup$ – Kuba Jul 26 '16 at 16:14
  • 1
    $\begingroup$ Surely this already has an answer elsewhere, e.g. (189), (13748), (51407), (67423), (83575), (98406), (99350), (99985), or is easily found in the documentation. $\endgroup$ – Mr.Wizard Jul 26 '16 at 16:30

Either transpose one list against the other or thread over them. Then flatten each sublist. Internally operations are looped over the lists all right, but this is how one normally does things in Mathematica.

transposed = Transpose[{list2, list1}];
threaded = Thread[{list2, list1}];
Flatten /@ transposed

{{1, a, b}, {2, c, d}, {3, e, f}, {4, g, h}}

SameQ[Flatten /@ transposed, Flatten /@ threaded]



One way could be

list3 = Partition[Flatten@Riffle[list2,list1], 3]

There a few things to watch out for though. Riffle truncates lists if the two arguments are not of the same length. Also, a more general way to generate your list2 might be to use Range, for example,


So all together you might try

list3 = Partition[Flatten@Riffle[
   list1], 3]

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