4
$\begingroup$

I have a list which looks like this:

{1,2,1,2,1,2}

I want to transform it into list that looks like this:

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

Where the first element in the index of item in the list, and the second element is the element of the list.

How do I do this in Mathematica?

$\endgroup$
  • 2
    $\begingroup$ look up MapIndexed in the docs. $\endgroup$ – kglr Mar 12 at 0:04
9
$\begingroup$
MapIndexed[Append[#2, #] &, {1, 2, 1, 2, 1, 2}]

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

Also

MapIndexed[Reverse@Flatten[{##}] &, {1, 2, 1, 2, 1, 2}]

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

Transpose[{Range @ Length @ #, #}] &@{1, 2, 1, 2, 1, 2}

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

Module[{i = 1}, {i++, #} & /@ {1, 2, 1, 2, 1, 2}]

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

| improve this answer | |
$\endgroup$
5
$\begingroup$
Thread[List[Range@Length@list, list]]

or

MapThread[{#, #2} &, {Range@Length@list, list}]
| 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.