Suppose I have a list of the form x={{a,b},{n1,n2,...} where n1,n2... are integers. I want to write a function that checks whether each of n1,n2, etc. is greater than a limit. If that's the case x is set to 0., else the function returns x.

fc[x_List] :=Module[{i, l}, l = Length[x[[2]]];
For[i = 1, i <= l, i++, If[x[[2, i]] > smax, x = 0.; Break[]]];

Let's try it:

smax = 2; x = {{1,5}, {1, 2, 3, 4}}; 
(*=> fc[0.] *)

and not 0. What am I doing wrong in the definition of fc ? Also, is there a way to write fc without usinf the For loop?

EDIT After discovering AnyTrue thanks to the answer of @SneezeFor16Min who mentions AllTrue the answer is

fc[x_List] := If[AnyTrue[x[[2]], # > smax &], 0., x]    
  • $\begingroup$ (1) Scan can replace For in this case. (2) x in the definition of fc is a List, not a Symbol, so x = 0. is equivalent to {{1,5}, {1, 2, 3, 4}} = 0. which won't work. You should use temporary variable for return. $\endgroup$ Jan 29, 2021 at 9:26
  • $\begingroup$ Or you can use GreaterThan[smax] (not a big deal). $\endgroup$ Jan 29, 2021 at 10:11

1 Answer 1


To extend my comment, I'd like to notice that we seldom need to write For loops ourselves in Mathematica; if any, it's slow and can be rewritten with stuff like Do or Scan. Here you just want to check if all elements satisfy some condition (i.e., do not exceed smax), which is already built in, VectorQ or AllTrue:

fc[x : {_, n_}] := If[VectorQ[n, # <= smax &], x, 0.]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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