For testing a condition on every element of a numpy.ndarray at once, as the title could suggest:
use numpy's np.all for that:
if np.all(a == 0):
# ...
Despite it is not lazy, np.all is vectorized and very fast
# arrays of zeros
>>> a = np.zeros((1000000))
>>> %timeit np.all(a == 0) # vectorized, very fast
10000 loops, best of 3: 34.5 µs per loop
>>>%timeit all(i == 0 for i in a) # not vectorized...
100 loops, best of 3: 19.3 ms per loop
# arrays of non-zeros
>>> b = np.ones((1000000))
>>> %timeit np.all(b == 0) # not lazy, iterates through all array
1000 loops, best of 3: 498 µs per loop
>>> %timeit all(i == 0 for i in b) # lazy, return false at first 1
1000000 loops, best of 3: 561 ns per loop
# n-D arrays of zeros
>>> c = a.reshape((100, 1000)) # 2D array
>>> %timeit np.all(c == 0)
10000 loops, best of 3: 34.7 µs per loop # works on n-dim arrays
>>> %timeit all(i == 0 for i in c) # wors for a 1D arrays only
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
For testing a condition on every element of a numpy.ndarray iteratively:
for i in range(n):
if a[i] == 0:
a[i] = 1
can be replaced by np.where
a = np.where(a == 0, 1, a) # set value '1' where condition is met
EDIT: precisions according to the OP's comments
#...supposed to do. Do you want to call a code fragment for every element?a? Python array or numpy array?