# Adding numbers to a list

Say you have the following list of 12 elements

X={"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"}


And I want to turn it into the following sorted list:

{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}


How do I achieve this? I've tried numerous methods such as using a "Print[]" within a For loop and StringReplace but I haven't figured it out. I'm new to mathematica. Thanks in advance for the help!

• Hi,brother or sister.If I have help you to solve this problem,click the check that left in my answer. – yode Mar 16 '16 at 1:35
• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Mar 16 '16 at 1:51
• Sort@Table["x" <> IntegerString[i], {i, 1, 12}] – user1066 Mar 16 '16 at 10:00

Basically, the problem is to join each element in the list with its index. The MapIndexed function is handy for this.

The function to apply for each element is a straightforward StringJoin:

f[x,y]=x<>ToString[y]


Overall, the solution is

Sort@MapIndexed[#1 <> ToString[First[#2]] &, X]


{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

X = {"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"};
n = IntegerString@Range@Length@X;


{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

Actually,I can tell you another secret to this

Sort@Table[TemplateApply["x<*i*>"], {i, 12}]


{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

• With[ {lst = Table["x", {12}]}, StringJoin[lst[[#]], IntegerString[#, 10, 2]] & /@ Range[Length@lst] ] will get you what you want if sorting is critical. – dwa Mar 16 '16 at 2:16
• @dwa Thanks for your good suggestion~ – yode Mar 16 '16 at 2:21

Note you could just do:

Sort["x" <> ToString[#] & /@ Range]


If you have list you can also use MapIndexed:

xs = ConstantArray["x", 12];
Sort@MapIndexed[#1 <> ToString[#2[]] &, xs]