As Jens says your approach is not very Mathematica-like, i.e., it doesn't make good use of Mathematica's strengths. Here is an implementation that I hope Jens would agree makes better use of those strengths. Although it is more concise than your method, it has more generality; you can pick the column where the index of the list element is inserted.
insertIndex[data_List, col_Integer] /; 0 < col <= Length[data[[1]]] + 1 :=
MapIndexed[Insert[#1, #2[[1]], col] &, data]
To digest this answer, you should look up MapIndexed
, Part
and Function
in the Documentation Center. The article under Part
will explain the [[ ]]
notation and article under Function
will explain the #1
, #2
, and &
stuff.
The rather elaborate formal argument pattern is designed restrict arguments to valid ones -- not perfectly, but usefully.
Testing
First I generate a list of 6 3-element lists.
data[n_] := With[{names = Alphabet[]}, Table[RandomSample[names, 3], n]]
SeedRandom[42]; test = data[6]
{{"n", "u", "e"}, {"c", "b", "g"}, {"a", "t", "e"},
{"d", "i", "m"}, {"a", "h", "i"}, {"w", "z", "g"}}
Then I have insertIndex
insert the index of each sublist at positions 1 to 4
Table[insertIndex[test, col], {col, Length[test[[1]]] + 1}]
{{{1, "n", "u", "e"}, {2, "c", "b", "g"}, {3, "a", "t", "e"},
{4, "d", "i", "m"}, {5, "a", "h", "i"}, {6, "w", "z", "g"}},
{{"n", 1, "u", "e"}, {"c", 2, "b", "g"}, {"a", 3, "t", "e"},
{"d", 4, "i", "m"}, {"a", 5, "h", "i"}, {"w", 6, "z", "g"}},
{{"n", "u", 1, "e"}, {"c", "b", 2, "g"}, {"a", "t", 3, "e"},
{"d", "i", 4, "m"}, {"a", "h", 5, "i"}, {"w", "z", 6, "g"}},
{{"n", "u", "e", 1}, {"c", "b", "g", 2}, {"a", "t", "e", 3},
{"d", "i", "m", 4}, {"a", "h", "i", 5}, {"w", "z", "g", 6}}}
insertColumns[list_ List]
to indicate a list is input. $\endgroup$ – Fred Kline Apr 16 '16 at 2:11