This question already has an answer here:

For example when would you use a Do loop over a For loop? For which tasks would you use Map, Table, Scan, et cetera? I'm quite new to Mathematica and I don't really get what the advantages of any of these loops are over the standard For loop whose use seems to be so harshly discouraged here on StackExchange.


marked as duplicate by Sjoerd C. de Vries, Michael E2, Artes, rm -rf Jan 15 '14 at 15:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    $\begingroup$ Regarding Do vs For: if you can use Do, do not use For. For is less readable and introduces global variables which you'd have to localize manually. For is not generally standard, it is just a convenient construct in some procedural languages. If you compare code using For with code equivalent using Do, it should be clear why Do is usually much more convenient in Mathematica. $\endgroup$ – Szabolcs Jan 2 '14 at 18:49
  • 2
    $\begingroup$ Regarding functional vs procedural (Table/Map vs Do), the functional approach typically gives better performance and more concise and readable code in Mathematica. You'll of course need to get used to thinking in terms of these constructs first, and if you're used to writing C code, using these will not come naturally right away. $\endgroup$ – Szabolcs Jan 2 '14 at 18:51
  • 4
    $\begingroup$ But in any case - use whatever makes you happy. Once performance becomes important, you´ll notice the differences. Otherwise your question is rather broad... $\endgroup$ – Yves Klett Jan 2 '14 at 18:55
  • 1
    $\begingroup$ Do can directly loop over the elements of a list, For can't. Compare Do[Print[i],{i,myList}] vs For[i=1,i<Length[myList],i++,Print[myList[[i]]]]. Of course, Map (/@) is shorter: Print/@myList. $\endgroup$ – Sjoerd C. de Vries Jan 2 '14 at 18:56
  • 2
    $\begingroup$ In the particular case of For, I think it's our collective experience that you very very rarely need to go "so general"; almost always there's a better alternative. $\endgroup$ – Rojo Jan 2 '14 at 19:02

Browse other questions tagged or ask your own question.