1

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!

Rock
  • 2,645
  • 8
  • 34
  • 46

5 Answers5

10

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
Jon Clements
  • 132,101
  • 31
  • 237
  • 267
2
In [16]: l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]

In [17]: l.count(0)
Out[17]: 5
avasal
  • 13,666
  • 4
  • 29
  • 47
2
li = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
print len(li) - sum(li)
eyquem
  • 25,715
  • 6
  • 36
  • 44
1

Your choice, whatever lets you sleep at night:

l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]

print l.count(0)
# or maybe:
print len(filter(lambda a: a == 0, l))
# or maybe:
print len([0 for x in l if x==0])
JHolta
  • 2,061
  • 1
  • 27
  • 26
1

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.

flonk
  • 3,387
  • 3
  • 22
  • 34