With an array like [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0], is there a quick way to return the number of 0(s), which is 5 in the example? Thanks!
5 Answers
Use list.count:
your_list.count(0)
And the help:
>>> help(list.count)
Help on method_descriptor:
count(...)
L.count(value) -> integer -- return number of occurrences of value
2 Comments
Rock
I feel ashamed for asking this question.
Jon Clements
@Rock well - on the plus side - you won't forget it any time soon ;)
You can speed things up by a factor of 100 by using arrays (, which only becomes important for large lists)...
This should be 100 times faster than my_list.count(0):
(my_array==0).sum()
However it only helps, if your data is already arranged as a numpy array (or you can manage to put it into a numpy array when it is created). Otherwise the conversion my_array = np.array(my_list) eats the time.