1

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?

BoLe
  • 5,819
  • 15
  • 33
Junaid Aftab
  • 1,000
  • 5
  • 11

2 Answers2

1

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

BoLe
  • 5,819
  • 15
  • 33
0

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]
nadlr
  • 405
  • 3
  • 10