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?

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

1 Answer 1


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

  • $\begingroup$ 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;) $\endgroup$
    – Bob Hanlon
    Sep 29, 2017 at 19:45
  • $\begingroup$ Gosh... perhaps we should start a contest for the ugliest solutions to problems! $\endgroup$ Sep 29, 2017 at 20:27

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