# How to check if every element of a list satisfies a condition inside an IF construct?

I have the list,

listx = {{0., -0.6}, {0.08, -1.}, {0.16, -0.9}, {0.24, 1.}, {0.32, 0.6}}


And I want to check if every second element satisfies both conditions ($$>= -1$$ && $$<= 1$$).

I have tried my luck with AllTrue but I can't seem to make it work, this is what I have until now,

If[Do[AllTrue[listx, listx[[k, 2]] >= -1 && listx[[k, 2]] <= 1], {k, 1, 5, 1}], Print["a"]]


Care to help me out?

Since you were on the right track, we can keep the code pretty similar to what you had and basically just remove the do loop:

If[AllTrue[listx, -1 <= #[[2]] <= 1 &], Print["a"]]


The #[[2]] specifies that it should test the second part of each element of listx. You could just use # there and replace listx with listx[[All,2]] as well.

Your Do loop does not return a True, so the clause in your If statement never evaluates.

hasValidSecondElement[{_, x_}] := x >= -1 && x <= 1
hasValidSecondElement[___] := False

AllTrue[listx, hasValidSecondElement]
(* True *)


I defined a helper function for readability. When you go back to this code, it is clear what the intention was for a line like AllTrue[listx, hasValidSecondElement].

Edit:

  If[SameQ @@ (-1 <= #2 <= 1 & @@@ listx), Print["true"],Print["false"]]


 n = Length@listx;
If[Total@Boole@Table[-1 <= listx[[k, 2]] <= 1, {k, n}] == n, Print["a"]]


Or

n = Length@listx;
If[Total@Boole[-1 <= #2 <= 1 & @@@ listx] == n, Print["a"]]

n = Length@listx;
If[Count[-1 <= #2 <= 1 & @@@ listx, True] == n, Print["a"]]

• Thank you very much, I'm gonna check it a little more and wait before marking it as solved, but I think you solved it!! Commented Dec 3, 2018 at 17:40

I think Thread allows for a really nice syntax here:

If[And @@ Thread[-1 <= listx[[All,2]] <= 1], Print["a"]]