Iteration Over a 1D Array :
The simplest form of iteration uses a for loop.
Example :
Python
import numpy as np arr = np.array([10, 20, 30, 40]) for x in arr: print(x) #output 10 20 30 40 Iteration Over a 2D Array :
When iterating a 2D array, each iteration gives a rowExample :
Python
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] Iteration Over Each Element in a 2D Array :
Python
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) for row in arr: for value in row: print(value) Iterating using np.nditer( ) :
nditer( ) allows iteration over each element, regardless of array dimensions
Python
import numpy as np arr = np.array([10, 20, 30, 40]) for x in np.nditer(arr): print(x) Iterating with Index :
Use ndenumerate( ) when you need both index and value
Python
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) for index, value in np.ndenumerate(arr): print(index, value) #output (0, 0) 1 (0, 1) 2 (0, 2) 3 (1, 0) 4 (1, 1) 5 (1, 2) 6