You can simply sum() the list False
is 0, True
is 1.
Other way would be to list.count()
the True
's:
prep = """import random
random.seed("count is faster then sum he said...")
data = random.choices([True,False],k=10000)"""
prog1 = "k = sum(data)"
prog2 = "l = data.count(True)"
prog3 = "j = len( [x for x in data if x] )"
import timeit
print(timeit.timeit(prog1,setup=prep, number = 1000))
print(timeit.timeit(prog2,setup=prep, number = 1000))
print(timeit.timeit(prog3,setup=prep, number = 1000))
Output:
0.32247100600034173 # sum( data )
0.12246353499995166 # data.count( True )
0.24579112000083114 # len( [x for x in data if x] )
Counting seems to be the right choice, its takes only about 45-50% of the time. Even the list-comp of len( [x for x in data if x] )
is faster than the sum.
Both methods are already covered in other questions: