8 Iterating Arrays
8 Iterating Arrays
Example
Iterate on the elements of the following 1-D array:
import numpy as np
for x in arr:
print(x)
Example
Iterate on the elements of the following 2-D array:
import numpy as np
for x in arr:
print(x)
## output
[1 2 3]
[4 5 6]
####To return the actual values, the scalars, we have to iterate the arrays in each
dimension.
Example
Iterate on each scalar element of the 2-D array:
import numpy as np
for x in arr:
for y in x:
print(y)
### output
1
2
3
4
5
6
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
##### To return the actual values, the scalars, we have to iterate the arrays in
each dimension.
Example
Iterate down to the scalars:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
Example
Iterate through the following 3-D array:
import numpy as np
for x in np.nditer(arr):
print(x)