8
$\begingroup$

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?

$\endgroup$
1
  • $\begingroup$ You should be using === instead of == here, since you are comparing symbols. $\endgroup$
    – J. M.'s torpor
    Nov 28 '19 at 23:24
8
$\begingroup$

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

If[Union@a == {yes}, Print["that's OK"]]
$\endgroup$
1
  • $\begingroup$ Thanks, this is my mean, but I didn't think Union works in this case $\endgroup$
    – Wisdom
    Nov 28 '19 at 6:17
13
$\begingroup$

You could also try AllTrue:

If[AllTrue[a, # == yes &], Print["that's OK"]]
$\endgroup$
1
  • $\begingroup$ Thanks a lot. this is more comprehensible $\endgroup$
    – Wisdom
    Nov 28 '19 at 7:00
8
$\begingroup$

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 *)
$\endgroup$
2
$\begingroup$

You can also Apply an old-fashioned logical And:

If[And @@ (# === yes & /@ a), Print["that's OK"]]
$\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.