How to Count True Values in Python?

Estimated read time 2 min read

To count the number of True values in Python, you can use any of the following approaches:

  1. Using the count() method of a list:
my_list = [True, False, True, True, False, True, False]
count = my_list.count(True)
print(count)  # Output: 4

In this approach, we use the count() method of a list, which returns the number of occurrences of a particular value. We pass True as the argument to count() to count the number of True values in the list.

  1. Using a loop:
my_list = [True, False, True, True, False, True, False]
count = 0
for value in my_list:
    if value == True:
        count += 1
print(count)  # Output: 4

In this approach, we use a loop to iterate through the list and manually count the number of True values by checking if each value is equal to True using an if statement, and incrementing the count if the condition is met.

  1. Using the sum() function with a list comprehension:
my_list = [True, False, True, True, False, True, False]
count = sum([1 for value in my_list if value == True])
print(count)  # Output: 4

In this approach, we use a list comprehension to create a list of 1s for each occurrence of True in the original list. Then, we use the sum() function to add up all the 1s, which gives us the count of True values in the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply