To count the number of True
values in Python, you can use any of the following approaches:
- 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.
- 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.
- 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 1
s for each occurrence of True
in the original list. Then, we use the sum()
function to add up all the 1
s, which gives us the count of True
values in the list.
+ There are no comments
Add yours