Iterating means going through elements one by one. A normal Python for loop works, and NumPy adds helpers for multi-dimensional arrays.
Iterate a 1-D array
Example
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)
Output
1
2
3
Iterate a 2-D array
A loop over a 2-D array gives you one row at a time:
Example
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for row in arr:
print(row)
Output
[1 2 3]
[4 5 6]
To reach every single value you need one loop per dimension:
Example
import numpy as np
arr = np.array([[1, 2], [3, 4]])
for row in arr:
for x in row:
print(x)
Output
1
2
3
4
np.nditer(): every element, any dimension
Example
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for x in np.nditer(arr):
print(x, end=" ")
Output
1 2 3 4 5 6 7 8
np.ndenumerate(): elements with their index
Example
import numpy as np
arr = np.array([[10, 20], [30, 40]])
for index, value in np.ndenumerate(arr):
print(index, value)
Output
(0, 0) 10
(0, 1) 20
(1, 0) 30
(1, 1) 40
Loops are fine for learning and for small arrays, but on real data prefer vectorized operations such as
arr * 2orarr.sum(). They do the same work in compiled code and are far faster.