

Compare the following: For[i=1, i <= n, i++, Do will do the same thing better.ĭo is more concise, thus both more readable and easier to write without mistakes. The typical use case of For is iterating over an integer range. I will simply argue that when we do need a procedural loop, For is nearly always the worst choice. Functional programming is usually the better choice in Mathematica, but procedural programming is also clearly needed in many situations. I want to make it clear at the beginning that the following arguments are not about functional vs procedural programming. Settling on For also tends to delay beginners in discovering more Mathematica-like programming paradigms, such as list-based and functional programming ( Table, Map, etc.) Unfortunately, For gives them lots of ways to shoot themselves in the foot, while providing virtually no benefits over alternatives such as Do. Many beginners coming from such languages will look for a "for loop" when they start using Mathematica. My biggest argument against For is that it hinders learning by encouraging error-prone, hard to read, and slow code.įor mimics the syntax of the for loop of C-like languages. If you are a seasoned Mathematica user, you won't find much to learn here.

The following is my personal opinion on why using For is harmful when learning Mathematica.

I have often told people, especially beginners, to avoid using For in favour of Do. If you are new to Mathematica, and were directed to this post, first see if you can use Table to solve your problem.
