3

I would like to take a one dimensional list, e.g., list1={1,2,3} and add a second column, e.g., list2={a,b,c} to get list3={{1,a},{2,b},{3,c}}.

I know that one can add a column to a matrix using Transpose and Join, but this doesn't seem to work for a simple list.

Michael E2
  • 235,386
  • 17
  • 334
  • 747
Rob
  • 141
  • 1
  • 2

3 Answers3

4

Let's try to do 10 ways.

Courtesy of @cvgmt in the comments under the OP

{list1, list2} // Transpose
{list1, list2} // Thread

My original answer

Inner[List, list1, list2, List]
ArrayReduce[Dot, {list1, list2}, 1]
ArrayReshape[Riffle[list1, list2], {Length@list1, 2}]
MapThread[List, {list1, list2}]
Table[{list1[[i]], list2[[i]]}, {i, 1, Length@list1}]

Another great recommendation by @cvgmt as a comment under this answer

Outer[List, list1, list2] // Diagonal

@Nasser's suggested solution

MapThread[{#1, #2} &, {list1, list2}]

@Michael E2 used J. M.'s function in the following way

columnAttach[{1, 2, 3}, {a, b, c}]

All of the above give

res

bmf
  • 15,157
  • 2
  • 26
  • 63
  • 2
    Or Outer[List, list1, list2] // Diagonal – cvgmt Jun 02 '23 at 01:02
  • 1
    I do not know if this counts different that one already given using MapThread. MapThread[{#1, #2} &, {list1, list2}] – Nasser Jun 02 '23 at 01:51
  • @cvgmt that's a very nice suggestion. Why don't you make it an answer with the other two ways in the comment under the OP? – bmf Jun 02 '23 at 03:41
  • @Nasser I guess it should be sufficiently different for an alternative answer :-) – bmf Jun 02 '23 at 03:41
  • 1
    may be you could collect these into your answer and see if we got 10 or not. I think we have 10 different ones already scattered in comments and in your answer.. – Nasser Jun 02 '23 at 03:56
  • @Nasser done :-) – bmf Jun 02 '23 at 04:21
  • 1
    Not meaning to offend anyone, but with regard to Outer I don’t think we should promote using $O(n^2)$ operations for $O(n)$ tasks. – Henrik Schumacher Jun 02 '23 at 12:30
3

Hmm, haven't seen this one yet:

Flatten[{list1, list2}, {2}]
lericr
  • 27,668
  • 1
  • 18
  • 64
2

Here we go again with another way:

Values@GroupBy[Join @@ (PositionIndex[#] & /@ {list1, list2}), Key, Keys]

({{1, a}, {2, b}, {3, c}})

Also:

Partition[Riffle[list1, list2], {Length@{list1, list2}}]
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44