Python | Boolean List AND and OR operations
Last Updated :
17 Apr, 2023
Sometimes, while working with Python list, we can have a problem in which we have a Boolean list and we need to find Boolean AND or OR of all elements in it. This kind of problem has application in Data Science domain. Let’s discuss an easy way to solve both these tasks.
Method #1 : AND operation – Using all() The solution to this problem is quite straight forward, but application awareness is required. The all() performs the Boolean AND of the list and returns the result.
Python3
test_list = [ True , True , False , True , False ]
print ("The original list is : " + str (test_list))
res = all (test_list)
print ("Result after performing AND among elements : " + str (res))
|
Output :
The original list is : [True, True, False, True, False]
Result after performing AND among elements : False
Time Complexity: O(n) where n is the number of elements in the list “test_list”. AND operation – Using all() performs n number of operations.
Auxiliary Space: O(1), constant extra space is required
Method #2 : OR operation – Using any() This task can be performed using any(). This checks for any True element in list and returns True in that case else returns a False.
Python3
test_list = [ True , True , False , True , False ]
print ("The original list is : " + str (test_list))
res = any (test_list)
print ("Result after performing OR among elements : " + str (res))
|
Output :
The original list is : [True, True, False, True, False]
Result after performing OR among elements : True
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(1) constant additional space needed
Method #3: Using reduce() and operator.and_ or operator.or_
This method is using python’s built-in reduce function and operator module’s and_ or or_ function to perform and or operation respectively. This method is more generic and can be applied to any iterable.
Python3
from functools import reduce
import operator
test_list = [ True , True , False , True , False ]
print ( "The original list is : " + str (test_list))
res = reduce (operator.and_, test_list)
print ( "Result after performing AND among elements : " + str (res))
res = reduce (operator.or_, test_list)
print ( "Result after performing OR among elements : " + str (res))
|
Output
The original list is : [True, True, False, True, False]
Result after performing AND among elements : False
Result after performing OR among elements : True
Time complexity for this method is O(n) and space complexity is O(1) as we are not using any extra data structure to store the values.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...