# An elementary question about For loop [duplicate]

Assume we have this For loop:

For[i=1,i<10,i++, i^2].

How can we put the squared values i^2 into a list?

• Table[i^2, {i, 9}]. Range^2. See this post.. – march Sep 29 '17 at 17:43
• It's not an exact duplicate but Szabolcs' answer there gives several alternatives along with explanation of why they are preferred. – Simon Woods Sep 29 '17 at 20:22

For loops are very ugly in Mathematica and should be avoided whenever possible. @march's solutions are so much more elegant.

But if you're wedded to the idea of using a For loop, here's a very ugly approach to your problem:

mylist = {};
For[i = 1, i < 10, i++, AppendTo[mylist, i^2]]


and then

mylist

• With For, an even uglier approach but more efficient than using AppendTo is flattening nested lists. mylist = {}; (For[i = 1, i < 10, i++, mylist = {mylist, i^2}]; mylist = mylist // Flatten;) – Bob Hanlon Sep 29 '17 at 19:45
• Gosh... perhaps we should start a contest for the ugliest solutions to problems! – David G. Stork Sep 29 '17 at 20:27