I'm building two lists, each to carry a different representation of the same set of objects. One list, list2, is constructed first; then the second list, list1, is built element-by-element using a translation function TwoQOneQ. That function relies on a second function, ExtractList, that takes as argument an integer and returns a unique list of three integers . All the machinery works as expected for a single argument, e.g.


Out[93]= {{2, 1, 2}}

Out[94]= {{1, 1, 2}}

as required.

However, when I embed TwoQOneQ inside a For loop, the loop runs only once:

For[i = 2, i <= 5, i++,



When I comment out the line with TwoQOneQ, the loop runs as expected:

For[i = 2, i <= 5, i++,





Also, when I increase the ceiling on i to i <= 6 or higher, Mathematica freezes. The icon at the bottom of my screen has a yellow circle to say the program's running code, but the grey cell bar on the side isn't black to say it is; the scroll bar rapidly shrinks as if there's a large amount of output, but nothing prints; and I have to close Mathematica through the Task Manager.

The full, simplified code is

ExtractList = 
  Function[k, {Mod[k - 1, 2] + 1, Mod[Quotient[k - 1, 2], 1] + 1, 
    Quotient[k - 1, 2] + 1}];

list2 = Tuples[{0, 1}, 4];
list1 = Table[{0}, {i, 0}];

(*translates a given state in second list into a given state in first list*)
TwoQOneQ = Function[TwoQ,
   OneQ = Table[{0}, {i, 0}];
   For[i = 1, i <= Length[TwoQ], i++,
    If[TwoQ[[i]] == 1, OneQ = Append[OneQ, ExtractList[i]], 
     OneQ = OneQ]];

For[i = 1, i <= 5, i++,

This problem has persisted through restarting Mathematica and restarting my computer.

  • 2
    $\begingroup$ I presume what's going on is that For does not localise its variables -- i appears multiple times here, and it is always the exact same object. $\endgroup$ – AccidentalFourierTransform Jul 27 '19 at 23:13
  • $\begingroup$ This appears to be a scoping problem. Your variable i is not localalized, and is changed by the function TwoQOneQ. $\endgroup$ – MelaGo Jul 27 '19 at 23:14
  • $\begingroup$ @AccidentalFourierTransform is right. Try Table[TwoQOneQ[list2[[i]]], {i, 1, 5}]. $\endgroup$ – Rohit Namjoshi Jul 27 '19 at 23:14
  • $\begingroup$ All three of you are right! The change works. @AccidentalFourierTransform was first; if you post your comment as a response I'll accept it as the answer. $\endgroup$ – Natavi Jul 27 '19 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.