# Merging Two Lists - Loops [closed]

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?

• Flatten /@ Transpose[{list2, list1}] good enough? Commented Jul 26, 2016 at 16:11
• @BlacKow no, Join[list2, list1, 2] :)
– Kuba
Commented Jul 26, 2016 at 16:11
• I would avoid looking for a loop to achieve this sort of stuff! There is always a better way in Mathematica.
– ktm
Commented Jul 26, 2016 at 16:12
• related: 113630 together with topics linked there.
– Kuba
Commented Jul 26, 2016 at 16:14
• Surely this already has an answer elsewhere, e.g. (189), (13748), (51407), (67423), (83575), (98406), (99350), (99985), or is easily found in the documentation. Commented Jul 26, 2016 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}];
Flatten /@ transposed


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

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


True

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,

 Range[Length@list1]


So all together you might try

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