Count True Booleans in a Python List
In this tutorial, we will learn how to count True Booleans in a Python List. There are 2 boolean values present. They are as following:
- True
- False
Some of the methods to count True Booleans are listed here:
Using count() Method
count()
method counts the number of occurrences of an element and returns it.
l=[True, True, False, False, True] x=l.count(True) print(x)
Output: 3
Using the sum() Method
sum()
method sums up the numbers in a list. True means 1 and False means 0. Hence, the sum()
method will add all 1’s and 0’s and will return the count of True Booleans present in the list.
l=[True, True, False, False, True] x=sum(l) print(x)
Output: 3
Using the filter() Method
filter()
method filters the elements present in the list based on the given condition.
l=[True, True, False, False, True] x=list(filter(None, l)) print(len(x))
Output: 3
Using list comprehension
List comprehension is a way to create a new list based on an existing list.
l=[True, True, False, False, True] x=sum(bool(i) for i in l) print(x)
Output: 3
Recommended Posts:
Leave a Reply