# How do I count zeros in sublists?

I have an array RandomInteger[1,{100,100}]. How do I count zeros in each sublist so that I have a list which gives the number of zeros of each sublist in the array?

• 100-Total[your_array_here,{2}] – ciao May 26 '20 at 4:45
• @ciao: Very cute solution! Thanks. – Garfield May 26 '20 at 5:08
• @Garfield it is not just cute though: it is lightning-fast too! It is pretty much guaranteed to beat any Map based solution by orders of magnitude in execution time. Of course you could generalize it as Length[array] - Total[array, {2}]. – MarcoB May 26 '20 at 5:19

Another method (also reasonably general?)

0 /.(Counts/@myArray)

• Or, as a slight alternative to the neat method given by @ciao in a comment Total[1-mylist,{2}] (which is independent of array dimensions). – user1066 May 26 '20 at 18:59
• Thanks for the accept. IMO a great answer was given in a comment by ciao. You are allowed answer your own question (and accept it as best and(?) up-vote it), and @J. M.'s technical difficulties (moderator) often encourages it. Maybe post an answer yourself incorporating this answer and the two modifications suggested in the comments, where it will 'jump out' at future visitors? IMO it is a pity that a 'power-tool' answer is 'buried' in the comments. Your question has the potential of attracting a lot of 'hits' from users with the very same query. – user1066 May 27 '20 at 11:19

Try this example

matrix=RandomInteger[1,{5,5}]


returns this

{{0,1,0,1,1},{0,1,0,0,1},{1,0,1,0,1},{1,1,1,0,0},{0,0,0,1,0}}


and then this

Map[Count[#,0]&,matrix]


returns

{2,3,2,2,4}

• Note that you can write Map[Count[0], matrix] as well, using the operator form. (+1) – MarcoB May 26 '20 at 5:21
• If a likely brand new user doesn't know about Map then I try to give them one simple broadly applicable idea for their first time. I understand, and usually mention but didn't this time, that there are almost always at least six different ways of doing anything in Mathematica AND that at least two of those are nearly completely incomprehensible to even moderately experienced users. And I understand that shaving a few seconds or even milliseconds off the run time is some people's only goal in life, far outweighing understandable methods that can be used to solve other problems in the future. – Bill May 26 '20 at 5:32
• I agree with the readability and simplicity argument. In fact, it was with those in mind that I proposed the operator form. The two forms are perfectly equivalent and have no difference in execution time but, in my opinion at least, I find the latter more readable than the pure function format, and just as general. – MarcoB May 26 '20 at 14:24