# Number elements in a list

I'm trying to learn more about list replacement without using Table. I have a list like this:

list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}}

Now, I want to modify the list elements, i.e. add the position of the respective elements in front of it and replace every element in the list with that:

listMod = {{{1->"a", 2->"b",3->"c"}, {1->"d", 2->"e", 3->"f"}, {1->"g", 2->"h", 3->"i"}}}
• Check MapIndexed. – Kuba Aug 17 '17 at 20:15
• Ah yes that works quite well, thank you! – holistic Aug 17 '17 at 20:27

list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};
Map[MapIndexed[First@#2 -> #1 &], #, {2}] &@list

(* Out: {{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"},
{1 -> "g", 2 -> "h", 3 -> "i"}}} *)
• Thank you, didn't about MapIndexed until now ;) – holistic Aug 17 '17 at 20:27
• @holistic You are very welcome :-) – MarcoB Aug 17 '17 at 20:28
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};

Apply[Rule, Map[Transpose[{Range@3, #}] &, list, {2}], {3}]

Or, more generally

num /@ Catenate@list

Or

Normal @ Map[PositionIndex, list, {2}] /. (a_ -> {b_}) :> b -> a
• Wow, thanks still trying to understand the last line ;) – holistic Aug 17 '17 at 20:29

You can use ReplacePart :

list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}}
ReplacePart[list,x:{i_,j_,k_}:> (k-> Extract[list,x])]

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

ReplacePart[] is known to be not efficient in terms of memory consumption and speed.

The advantage here is that you have a great flexiblity to do more complicated remplacements. For example you can put constraints on the patterns i_,j_,k_,x

MapIndexed[#2[[3]] -> #1 &, list, {3}]

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

Map[Thread[Range@Length@# -> #] &, list, {2}]

MapIndexed[#2[[3]] -> #1 &, list, {3}] ==
Map[Thread[Range@Length@# -> #] &, list, {2}] == listMod

True

Module[{i = 1}, i++ -> # & /@ #] & /@ # & /@ list

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}