Python | Boolean List AND and OR operations

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Boolean List AND and OR operations
# AND Operation - Using all()
  
# initialize list
test_list = [True, True, False, True, False]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Boolean List AND and OR operations
# AND Operation - Using all()
res = all(test_list)
  
# printing result
print("Result after performing AND among elements : " + str(res))

chevron_right


Output :



The original list is : [True, True, False, True, False]
Result after performing AND among elements : False

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Boolean List AND and OR operations
# OR operation - Using any()
  
# initialize list
test_list = [True, True, False, True, False]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Boolean List AND and OR operations
# OR operation - Using any()
res = any(test_list)
  
# printing result
print("Result after performing OR among elements : " + str(res))

chevron_right


Output :

The original list is : [True, True, False, True, False]
Result after performing OR among elements : True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.