Message Boards Message Boards


Making And[] and Or[] work with lists

Posted 5 months ago
2 Replies
0 Total Likes

Making And[] and Or[] work with lists

george woodrow

I often have a list of Boolean values that I want to see if they are all True, all False, etc. Unfortunately, And[] and Or[] do not work with lists:

In[1]:= And[{True, False, True}]

Out[1]= {True, False, True}

It needs the arguments to not be in a list:

In[2]:= And[True, False, True]

Out[2]= False

I tried a number of ways to make this work, but I came across an elegant solution:

In[3]:= ReplacePart[{True, False, True}, 0 -> And]

Out[3]= False

This works with an assigned list.

In[4]:= myBools1 = {True, True, True};
myBools2 = {True, False, True};

In[6]:= ReplacePart[myBools1, 0 -> And]

Out[6]= True

In[7]:= ReplacePart[myBools2, 0 -> And]

Out[7]= False

In[8]:= ReplacePart[myBools2, 0 -> Or]

Out[8]= True

This functionality is in the Generalizations part of the documentation for ReplacePart[], but I missed it, and perhaps others might miss it as well.

This trick also works with a lot of other functions.

2 Replies
Posted 5 months ago

Hi George,

Other ways to do this

And @@ {True, False, True}
(* False *)

AllTrue[{True, False, True}, Identity]
(* False *)

And[Evaluate[Sequence @@ {True, False, True}]]
(* False *)

Or @@ {True, False, True}
(* True *)

Thanks -- I'll add them to my toolkit.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract