[python] Test if numpy array contains only zeros

We initialize a numpy array with zeros as bellow:


But how do we check whether all elements in a given n*n numpy array matrix is zero.
The method just need to return a True if all the values are indeed zero.

This question is related to python numpy

The answer is

The other answers posted here will work, but the clearest and most efficient function to use is numpy.any():

>>> all_zeros = not np.any(a)


>>> all_zeros = not a.any()
  • This is preferred over numpy.all(a==0) because it uses less RAM. (It does not require the temporary array created by the a==0 term.)
  • Also, it is faster than numpy.count_nonzero(a) because it can return immediately when the first nonzero element has been found.
    • Edit: As @Rachel pointed out in the comments, np.any() no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.

Similar questions with python tag:

Similar questions with numpy tag: