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$
1
  • 2
    $\begingroup$ look up MapIndexed in the docs. $\endgroup$
    – kglr
    Mar 12, 2020 at 0:04

2 Answers 2

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}}

$\endgroup$
5
$\begingroup$
Thread[List[Range@Length@list, list]]

or

MapThread[{#, #2} &, {Range@Length@list, list}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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