AND operation for Boolean array's elements
I have a variable length Boolean array as shown below:
ARR = [True, False, True, False,...]
Is there any simplest way (single line) to perform AND operation for all elements, as below?
ARR[0] and ARR[1] and ARR[2] and ARR[3] and ARR[*]...
Solution 1:
There is a builtin, called all
, which will and
together all its arguments. For example:
>>> ARR = [True, False, True, False,]
>>> all(ARR)
False
And:
>>> ARR2 = [True, True, True,]
>>> all(ARR2)
True
More
The argument to all
need not be a list of booleans. Anything can be used as long as python can evaluate it to true or false. For example:
>>> all([True, 10, 'name'])
True
>>> all([True, 0, 'name'])
False
Solution 2:
Since you want the and
operation done, it should return True if all the elements in the list are True. So this simple line will do:
print(False not in bool_list)
This line looks for a False in the given list, thus technically doing the and
operation