1
$\begingroup$

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?

$\endgroup$
7
  • $\begingroup$ Flatten /@ Transpose[{list2, list1}] good enough? $\endgroup$
    – BlacKow
    Commented Jul 26, 2016 at 16:11
  • 6
    $\begingroup$ @BlacKow no, Join[list2, list1, 2] :) $\endgroup$
    – Kuba
    Commented Jul 26, 2016 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$
    – ktm
    Commented Jul 26, 2016 at 16:12
  • $\begingroup$ related: 113630 together with topics linked there. $\endgroup$
    – Kuba
    Commented Jul 26, 2016 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
    Commented Jul 26, 2016 at 16:30

2 Answers 2

1
$\begingroup$

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]

True

$\endgroup$
0
$\begingroup$

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]
$\endgroup$

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