5
$\begingroup$

How do I insert "Z" and then a number going from 1 to end (without space) in a list?

I have the following list:

Input:

list = {{1, 1}, {2, 1}, {3, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}}

Output:

{Z1, 1, 1}, {Z2, 2, 1},{Z3, 3, 1}...

I have tried using the commando Insert and looking at inserting at several positions, but without luck.

$\endgroup$
1
  • $\begingroup$ you want Z1 or "Z1"? $\endgroup$
    – Kuba
    Commented Nov 6, 2015 at 6:41

3 Answers 3

7
$\begingroup$

Using MapIndexed[]:

list = {{1, 1}, {2, 1}, {3, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}};
MapIndexed[Prepend[#1, StringJoin["Z", ToString[First[#2]]]] &, list]
   {{"Z1", 1, 1}, {"Z2", 2, 1}, {"Z3", 3, 1}, {"Z4", 5, 1}, {"Z5", 1, 2},
    {"Z6", 2, 2}, {"Z7", 3, 2}}
$\endgroup$
7
$\begingroup$
Flatten /@ Transpose[{"Z" <> ToString @ # & /@ Range@Length@list, list}]

{{"Z1", 1, 1}, {"Z2", 2, 1}, {"Z3", 3, 1}, {"Z4", 5, 1}, {"Z5", 1, 2}, {"Z6", 2, 2}, {"Z7", 3, 2}}

Or

MapThread[Prepend, {list, "Z" <> ToString @ # & /@ Range@Length@list}]

Or

Join @@@ Transpose@{Array[{"Z" <> ToString @ #} &, {Length@list}], list}

Or

i = 1;
list /. {a__?NumberQ} :> {"Z" <> ToString[i++], a}

Or with Insert

Insert[list[[#]], "Z" <> ToString @ #, 1] & /@ Range@Length@list
$\endgroup$
1
  • $\begingroup$ Would be the the same coding $\endgroup$
    – eldo
    Commented Nov 5, 2015 at 12:36
4
$\begingroup$

I think this is a problem where Table provides a straight-forward solution.

list = {{1, 1}, {2, 1}, {3, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}};
Table[{"Z" <> ToString[i], Sequence @@ list[[i]]}, {i, Length[list]}]

{{"Z1", 1, 1}, {"Z2", 2, 1}, {"Z3", 3, 1}, {"Z4", 5, 1}, {"Z5", 1, 2}, {"Z6", 2, 2}, {"Z7", 3, 2}}

Since list is a simple list of pairs, one might even consider

Table[{"Z" <> ToString[i], list[[i, 1]], list[[i, 2]]}, {i, Length[list]}]
$\endgroup$
2
  • $\begingroup$ Let's say i have a list = {x, 1 2 3}, {y, 4 5 6}. How do I add an element at the end of each {}. So the output would be: {x, 1 2 3, "element"}, {y, 4 5 6, "element"} $\endgroup$
    – Rob1234
    Commented Nov 5, 2015 at 13:32
  • $\begingroup$ @Rob1234. This is an answer to what you asked. Why are you asking something different and unclear in a comment to my answer? That is not appropriate behavior on this site. $\endgroup$
    – m_goldberg
    Commented Nov 5, 2015 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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