+

Python | Count true boolean values ​​in a list

Examples :

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

Method # 1: Using comprehension list

One of the easy ways to count true booleans in a list is to use a list.

# Python3 program for counting true boolean values ​​in a list

 

def count (lst):

 

return sum ( bool (x) fo r x in lst)

 
# Driver code

lst = [ True , False , True , True , False ]

print (count (lst))

Exit:

 3 

Method # 2: Using sum()

# Python3 program for calculating true logs values ​​in the list

 

def count (lst):

 

  return sum (lst)

 
# Driver code

lst = [ True , False , True , True , False ]

print (count (lst))

Exit:

3

A more reliable and transparent way to use sum is shown below.

def count (lst):

 

return sum ( 1 for x in lst if x)

Method # 3: method count()

# Python3 program for counting true boolean values ​​in a list

  

def count (lst):

 

return lst.count ( True )

 
# Driver code

lst = [ True , False , True , True , False ]

print (count (lst))

Exit:

 3  

Method number 4: filter()

# Python3 program for counting true booleans values ​​in the list

 

def count (lst):

 

return len ( list ( filter ( None , lst)))

  
# Driver code

lst = [ True , False , True , True , False ]

print (count ( lst))

Exit:

 3 
Get Solution for free from DataCamp guru