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.
# Python3 program to count True booleans in a list def count(lst): return sum(bool(x) for x in lst) # Driver codelst = [True, False, True, True, False]print(count(lst)) |
Output:
3
Method #2 : Using sum()
# Python3 program to count True booleans in a list def count(lst): return sum(lst) # Driver codelst = [True, False, True, True, False]print(count(lst)) |
Output:
3
A more robust and transparent method to use sum is given below.
def count(lst): return sum(1 for x in lst if x) |
Method #3 : count() method
# Python3 program to count True booleans in a list def count(lst): return lst.count(True) # Driver codelst = [True, False, True, True, False]print(count(lst)) |
Output:
3
Method #4 : filter()
# Python3 program to count True booleans in a list def count(lst): return len(list(filter(None, lst))) # Driver codelst = [True, False, True, True, False]print(count(lst)) |
Output:
3




.png)