If I have a list of conditions:


and I want to use an If[] statement to test the intersection of these conditions (or, more generally, any subset of them, but let's start with the basic case first):


How would I do that?

  • 2
    $\begingroup$ Something like conds = {cond1, cond2, cond3}; If[And @@ conds, a, b]? $\endgroup$ – J. M. will be back soon Oct 6 '12 at 13:23
  • $\begingroup$ Yes. Thanks J.M. I feel like I'm asking lots of quite trivial questions, but I have yet to get a feel for the syntax, and haven't got a good idea yet of what I need to search for in the documentation to find what I need. $\endgroup$ – Ooku Oct 6 '12 at 13:33

Don't worry about whether these are trivial questions: they are good opportunities to explain a little more about Mathematica's syntax.

The first point is that what you already had works fine. You can confirm this using FullForm.

If[cond1 && cond2 && cond3, a, b] // FullForm

If you preferred, you could type out the And construction explicitly.

J.M.'s comment invokes the Apply function to change the Head of a List of things, in this case the conditions, to And.

And @@ {cond1, cond2, cond3} // FullForm
(* And[cond1,cond2,cond3] *)

Or equivalently

FullForm[Apply[And, {cond1, cond2, cond3}]]
(* And[cond1,cond2,cond3] *)

The FullForm is just for explication; you wouldn't use it in normal operations. So the short syntax for the above is:

And @@ {cond1, cond2, cond3}
(* cond1&&cond2&&cond3 *)

The usefulness of storing your list of conditions as a list is that it is then easier to use various other list-manipulation techniques to get those subsets of conditions mentioned in your question.

And @@ (Most@{cond1, cond2, cond3})
(* cond1&&cond2 *)

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.