# how to write a condition for all elements of a list

I have a list

a={no,no,no,no};


now I can want to an If so that if all elements of the above list are "yes" it does something for example printing sth, I tried

a[[All]]=yes;

If[a[[All]]==yes, Print["that's OK"]];


but I know my command is wrong, any idea?

• You should be using === instead of == here, since you are comparing symbols. Nov 28 '19 at 23:24

Not sure what you're trying to do, but for your specific example, the following works:

If[Union@a == {yes}, Print["that's OK"]]

• Thanks, this is my mean, but I didn't think Union works in this case Nov 28 '19 at 6:17

You could also try AllTrue:

If[AllTrue[a, # == yes &], Print["that's OK"]]

• Thanks a lot. this is more comprehensible Nov 28 '19 at 7:00

An even more expressive approach (in my opinion at least) is to use ContainsOnly:

If[ContainsOnly[{yes}]@a, Print["that's OK"]];
(* that's OK *)


You can also Apply an old-fashioned logical And:

If[And @@ (# === yes & /@ a), Print["that's OK"]]