# Tagging a list of lists

This is probably a stupid question, but I am having problems trying to tag a list with identifying integers.

For example I have tried to tag {{a,b},{c,d},{e,f}} into {{a,b,1},{c,d,2},{e,f,3}}, via:

For[i==1,i<4,i++,Insert[{{a,b},{c,d},{e,f}}[[i]],i,3]]


and

For[i==1,i<4,i++,Append[{{a,b},{c,d},{e,f}}[[i]],i]]


and

Do[Insert[{{a,b},{c,d},{e,f}}[[i]],i,3],{i,3}].


However nothing so far has been successful. Any help would be appreciated.

Also note that I would like to be able to remove these tags later.

• As @tomd points out, possible duplicate of this and this and this. Oct 20, 2017 at 11:32

How about using MapIndexed :

list = {{a, b}, {c, d}, {e, f}};
tagged = MapIndexed[Append[#1, First@#2] &, list]

{{a, b, 1}, {c, d, 2}, {e, f, 3}}


To remove the tags later, you can do

Most /@ tagged

{{a, b}, {c, d}, {e, f}}


Edit: Thanks to tomd for pointing out kglr's syntactic wonder :

MapIndexed[ Join, list ]

{{a, b, 1}, {c, d, 2}, {e, f, 3}}


As kglr points out, the operator form can also be convenient :

MapIndexed[Join] @ list

{{a, b, 1}, {c, d, 2}, {e, f, 3}}

• (+1) Or, as kglr has shown us here, MapIndexed[Join, list]. Just for fun: MapIndexed[Join[#1, #2 - 1] &, list] Oct 20, 2017 at 11:29

Two possibilities (there are many more):

list = {{a, b}, {c, d}, {e, f}};

Flatten /@ Transpose[{list, Range[Length[list]]}]
i = 1; Join[#, {i++}] & /@ list


both of which give

(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)


If you really want to use Do and Insert, you need to remember that Do does not produce an output by default, and Insert doesn't modify the list in its first argument (it just creates a new list). But you could use Sow and Reap, for example:

Reap[Do[Sow@Insert[list[[i]], i, -1], {i, Length[list]}]][[-1, 1]]

(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)


To modify list directly in a Do loop, you could use AppendTo:

Do[AppendTo[list[[i]], i], {i, Length[list]}]
list

(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)


You might also consider tagging by PositionIndex

listindex = PositionIndex[list]

(* <|{a, b} -> {1}, {c, d} -> {2}, {e, f} -> {3}|> *)


which you can use to get the index of any element of list by, for example

listindex[{c, d}]

(* {2} *)