Python | Count true booleans in a list

Given a list of booleans, write a Python program to find the count of true booleans in the given list.

Examples:

Input : [True, False, True, True, False]
Output : 3

Input : [False, True, False, True]
Output : 2

 
Method #1 : Using List comprehension



One simple method to count True booleans in a list is using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count True booleans in a list
  
def count(lst):
  
    return sum(bool(x) for x in lst)
      
# Driver code
lst = [True, False, True, True, False]
print(count(lst))

chevron_right


Output:

3

 
Method #2 : Using sum()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count True booleans in a list
  
def count(lst):
      
    return sum(lst)
      
# Driver code
lst = [True, False, True, True, False]
print(count(lst))

chevron_right


Output:

3

A more robust and transparent method to use sum is given below.

filter_none

edit
close

play_arrow

link
brightness_4
code

def count(lst):
      
    return sum(1 for x in lst if x)

chevron_right


 
Method #3 : count() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count True booleans in a list
  
def count(lst):
      
    return lst.count(True)
      
# Driver code
lst = [True, False, True, True, False]
print(count(lst))

chevron_right


Output:

3

 
Method #4 : filter()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count True booleans in a list
  
def count(lst):
      
    return len(list(filter(None, lst)))
      
# Driver code
lst = [True, False, True, True, False]
print(count(lst))

chevron_right


Output:

3


My Personal Notes arrow_drop_up


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.