2

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!

1
  • There are plenty of duplicates here and online... Commented Mar 1, 2013 at 7:52

5 Answers 5

12

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
Sign up to request clarification or add additional context in comments.

2 Comments

I feel ashamed for asking this question.
@Rock well - on the plus side - you won't forget it any time soon ;)
3
li = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
print len(li) - sum(li)

Comments

2
In [16]: l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]

In [17]: l.count(0)
Out[17]: 5

Comments

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])

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.