Related Articles

# Python | Count true booleans in a list

• Last Updated : 25 Jun, 2019

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 code``lst ``=` `[``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 code``lst ``=` `[``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 code``lst ``=` `[``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 code``lst ``=` `[``True``, ``False``, ``True``, ``True``, ``False``]``print``(count(lst))`
Output:
```3
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up