Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a list {element,...} to a list of tuples {{i,element},...}?

Tags:

Given some list

numbers = {2,3,5,7,11,13};

How do I translate this to

translatedNumbers = {{1,2},{2,3},{3,5},{4,7},{5,11},{6,13}}

concisely?

I am aware of how to do this using the procedural style of programming as follows:

Module[{lst = {}, numbers = {2, 3, 5, 7, 11, 13}},
  Do[AppendTo[lst, {i, numbers[[i]]}], {i, 1, Length@numbers}]; lst]

But such is fairly verbose for what seems to me to be a simple operation. For example the haskell equivalent of this is

numbers = zip [1..] [2,3,5,7,11,13]

I can't help but think that there is a more concise way of "indexing" a list of numbers in Mathematica.

Potential Answer

Apparently I'm not allowed to answer my own question after having had a lightbulb go off unless I have 100 "rep". So I'll just put my answer here. Let me know if I should do anything differently then I have done.

Well I'm feeling a little silly now after having asked this. For if I treat mathematica lists as a matrix I'm able to transpose them. Thus an answer (perhaps not the best) to my question is as follows:

Transpose[{Range@6, {2, 3, 5, 7, 11, 13}}]

Edited to work for arbitrary input lists, I think something like:

With[{lst={2, 3, 5, 7, 11, 13}},Transpose[{Range@Length@lst,lst}]]

will work. Could I do any better?