1
$\begingroup$

Consider the following highly artificial example:

list = {{1, 2, 3, 4}};
While[Length[list[[1]]] > 3,
  If[RandomReal[{0, 1}] < 0.2,
    list = {};
    ,
    list = {{1, 2, 3}, {}};
    ];
];

Some 20% of the time here, you'll see the error:

Part::partw: Part 1 of {} does not exist. >>

How can we avoid this error if we are only allowed to modify the clause in the While loop and must have the Length[list[[1]]] > 3 query somewhere in the clause statement? Can we have an incident where list = {} cause a termination of the loop or ask for this to satisfy the loop clause?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! To interact better with this site it is recommended to register your account. I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Artes Dec 8 '14 at 17:30
0
$\begingroup$

Perhaps

list = {{1, 2, 3, 4}};
While[list =!= {} && Length[list[[1]]] > 3, 
  If[RandomReal[{0, 1}] < 0.2, list = {};, list = {{1, 2, 3}, {}};];];

list
(* {{1,2,3},{}} *)

or

ClearAll[list];
list = {{1, 2, 3, 4}};
While[Length[list[[1]]] > 3, 
  If[RandomReal[{0, 1}] < 0.2, Break[], list = {{1, 2, 3}, {}};];];

list
(* {{1,2,3},{}} *)

or

ClearAll[list];
list = {{1, 2, 3, 4}};
Catch[While[Length[list[[1]]] > 3, 
   If[RandomReal[{0, 1}] < 0.2, Throw[{}];, list = {{1, 2, 3}, {}};];]];

list
(* {{1,2,3},{}} *)
$\endgroup$

Your Answer

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

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