5
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ As @tomd points out, possible duplicate of this and this and this. $\endgroup$ – aardvark2012 Oct 20 '17 at 11:32
7
$\begingroup$

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}}
$\endgroup$
  • 4
    $\begingroup$ (+1) Or, as kglr has shown us here, MapIndexed[Join, list]. Just for fun: MapIndexed[Join[#1, #2 - 1] &, list] $\endgroup$ – user1066 Oct 20 '17 at 11:29
4
$\begingroup$

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} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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