5
$\begingroup$

Consider

listMerge[list1_, list2_] := Thread[({#1, #2}) &[list1, list2]]
listMerge[{1,2,3}, {4,5,6}] (* {{1,4}, {2,5}, {3,6}} *)

Is there a built-in function in Mathematica that already does what listMerge does (ideally one that handles more than 2 arguments)?

$\endgroup$
10
$\begingroup$

Just use Transpose

listMerge[list1_, list2_] := Transpose[{list1, list2}]

listMerge[{1, 2, 3}, {4, 5, 6}]

{{1,4}, {2,5}, {3,6}}

Or

Transpose[{{1,2,3}, {4,5,6}}]

{{1,4}, {2,5}, {3,6}}

listMerge[list_] := Transpose[list]
listMerge[{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}]

{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}

| improve this answer | |
$\endgroup$
8
$\begingroup$

You can define listMerge as the Composition of Thread and List (or Transpose and List)

ClearAll[listMerge1, listMerge2, listMerge3, listMerge4, listMerge5]
listMerge1 =  Thread @* List;
listMerge2 =  Transpose @* List;
listMerge3 = Thread[{##}] &;
listMerge4 = Transpose[{##}] &;
listMerge5 = Join[## & @@ Map[List, {##}, {-1}], 2] &;

listMerge1[{1, 2, 3}, {4, 5, 6}]

{{1, 4}, {2, 5}, {3, 6}}

Equal @@ (#[{1, 2, 3}, {4, 5, 6}] & /@ 
  {listMerge1, listMerge2, listMerge3, listMerge4, listMerge5})

True

listMerge1[{1, 2, 3}, {4, 5, 6}, {7, 8, 9}]

{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}

Equal @@ (#[{1, 2, 3}, {4, 5, 6}, {7, 8, 9}] & /@ 
  {listMerge1, listMerge2, listMerge3, listMerge4, listMerge5})

True

| improve this answer | |
$\endgroup$

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.