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)
or
>>> 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 thea==0
term.) Also, it is faster thannumpy.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.
- Edit: As @Rachel pointed out in the comments,