NumPy Array Iterating

🔁 NumPy Array Iteration

Iterating through NumPy arrays means accessing elements one-by-one using loops.
NumPy provides efficient ways to iterate through 1D, 2D, 3D arrays, including vectorized methods.


1. Iterating a 1D Array


 

Output:

1
2
3
4

2. Iterating a 2D Array (Row by Row)


 

Output:

[1 2 3]
[4 5 6]

3. Iterating 2D Array Element-by-Element


 

Output:

1
2
3
4
5
6

4. Iterating a 3D Array


 


🔹 Iterating Inside 3D

for block in arr:
for row in block:
for item in row:
print(item)

🚀 Better Way: np.nditer()

nditer() allows fast iteration over any dimension array.


 

Output:

1
2
3
4
5
6

Iterating with Data Type Conversion


 


🔁 Iterating with Index using ndenumerate()

Useful when you need index + value.


 

Output:

(0, 0) 10
(0, 1) 20
(1, 0) 30
(1, 1) 40

Summary Table

MethodBest ForExample
Simple for1D arraysfor x in arr
Nested Loop2D/3D arraysfor row in arr:
np.nditer()Fast iteration for any dimensionfor x in np.nditer(arr)
np.ndenumerate()Iteration with indexfor idx, val in np.ndenumerate(arr)

🎯 Practical Final Example


 

You may also like...