I\'d like to combine two lists. If I have the following two lists: {a,b,c,d}
and {1,2,3,4}
what do I need to do so that I get {{a,1}, {b,2},
An esoteric method is Flatten
, which (from the Help Section on Flatten) also allows Transpose of a 'ragged' array.
Flatten[ {{a, b, c, d}, {1, 2, 3, 4, 5}}, {{2}, {1}}]
Out[6]= {{a, 1}, {b, 2}, {c, 3}, {d, 4}, {5}}
listA={a,b,c,d};
listB=[1,2,3,4};
table=Transpose@{# & @@@ listA, # & @@@ listB}
Here is one way:
Transpose[{{a, b, c, d}, {1, 2, 3, 4}}]
This is a great question. I had become stuck thinking there was a default way to do this with Table, but not so. The answers below are fairly intuitive, and can be easily generalized to other similar situations.
l1 = {a,b,c,d};
l2 = {1,2,3,4};
pairs = Table[{l1[[i]], l2[[i]]}, {i, 1, Length[l1]}]
MapThread does this sort of thing also. This is less elegant than Howard's MapThread solution, but also more readable in some sense. Look at MapThread docs. The function is defined inline (pure function):
pairs = MapThread[{#1, #2} &, {l1, l2}]
If you have lists with the columns of a matrix:
l = Table[Subscript[g, Sequence[j, i]], {i, 5}, {j, 5}]
Transpose will give you the rows:
Transpose@l // MatrixForm
In case a, b, c, d themselves are also list, use the following:
MapThread[Flatten[{#1[[All]],#2}]&,{l1,l2}]//TableForm