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,827
  • 8
  • 35
  • 47

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
  • 138,671
  • 33
  • 247
  • 280
3
li = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
print len(li) - sum(li)
eyquem
  • 26,771
  • 7
  • 38
  • 46
2
In [16]: l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]

In [17]: l.count(0)
Out[17]: 5
avasal
  • 14,350
  • 4
  • 31
  • 47
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])
b0bz
  • 2,140
  • 1
  • 27
  • 27
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,726
  • 3
  • 24
  • 37