I often need to merge two lists like the following:



in a way to ideally obtain a new list such as:

$C = \{\{0.1,x_{1}\}, \{0.2,x_{21}\}, \{0.2,x_{22}\}, \{0.2, x_{23}\},\{0.3,x_{31}\}, \{0.3,x_{32}\}, \{0.3, x_{33}\}, \ldots, \{1, x_N\}\}$

At present I do this by inspecting the lists and manually associating them in the appropriate way. In above example, I would do




where S is the position of the last element that contains three entries in the $B$ list.

These lists are typically very long, and I wonder whether there is a way to do this efficiently.

  • $\begingroup$ A related thread. You'll be particularly interested in the use of Flatten[]. $\endgroup$ – J. M. is in limbo Jun 4 '15 at 20:29
  • 2
    $\begingroup$ Flatten[Tuples /@ (Transpose@{a, b}), 1]? $\endgroup$ – N.J.Evans Jun 4 '15 at 20:36
  • $\begingroup$ closely related $\endgroup$ – Kuba Jun 4 '15 at 20:40
  • 2
    $\begingroup$ Also Function[Null, {##}, Listable][Flatten@alist, blist]~Flatten~1 $\endgroup$ – garej Feb 24 '16 at 13:00

I feel like it is a duplicate but I can't find it now.

MapThread[Apply[Sequence]@*Tuples@*List, {alist, blist}]

enter image description here


Flatten[Tuples /@ Transpose[{alist, blist}], 1]


Flatten[MapThread[Thread[{#[[1]], #2}] &, {alist, blist}], 1]

You might have to change this slightly for your particular problem.

    A = Table[{0.1 n}, {n, 1, 10}]
    B = Array[Subscript[x, ##] &, {10, 3}]
    Map[Flatten, Apply[Prepend, MapThread[Prepend, {A, B}], {1}]]
Join @@ (Thread /@ Thread[{Flatten @ a, b}])      

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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