NumPy Array Iterating

🔁 NumPy Array Iteration (Complete Guide with Examples)

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

import numpy as np

arr = np.array([1, 2, 3, 4])

for x in arr:
print(x)

Output:

1
2
3
4

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

arr = np.array([[1, 2, 3], [4, 5, 6]])

for row in arr:
print(row)

Output:

[1 2 3]
[4 5 6]

3. Iterating 2D Array Element-by-Element

arr = np.array([[1, 2, 3], [4, 5, 6]])

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

Output:

1
2
3
4
5
6

4. Iterating a 3D Array

arr = np.array([ [[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]] ])

for block in arr:
print("Block:", block)


🔹 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.

arr = np.array([[1,2,3],[4,5,6]])

for x in np.nditer(arr):
print(x)

Output:

1
2
3
4
5
6

Iterating with Data Type Conversion

arr = np.array([1,2,3,4])

for x in np.nditer(arr, flags=['buffered'], op_dtypes=['float']):
print(x)


🔁 Iterating with Index using ndenumerate()

Useful when you need index + value.

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

Summary Table

Method Best For Example
Simple for 1D arrays for x in arr
Nested Loop 2D/3D arrays for row in arr:
np.nditer() Fast iteration for any dimension for x in np.nditer(arr)
np.ndenumerate() Iteration with index for idx, val in np.ndenumerate(arr)

🎯 Practical Final Example

arr = np.arange(1,10).reshape(3,3)

for index, value in np.ndenumerate(arr):
print(f"Index {index} = {value}")

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *