Iterating Over Elements of a NumPy Array


NumPy Array - Iterate over elements

To iterate over elements of a numpy array, you can use numpy.nditer iterator object.

numpy.nditer provides Python’s standard Iterator interface to visit each of the element in the numpy array. We can use For loop statement to traverse the elements of this iterator object.

Note: NumPy array with any number of dimensions can be iterated.

Examples

1. Iterate over elements of given 2D numpy array

In the following example, we have a 2D array, and we use numpy.nditer to print all the elements of the array.

Python Program

import numpy as np

#2D array
a = (np.arange(8)*2).reshape(2,4)

#print array
print("The array\n",a)

print("\nIterating over all the elemnets of array")
#iterate over elements of the array
for x in np.nditer(a):
	print(x, end=' ')

Output

Summary

In this Numpy Tutorial, we learned how to iterate over elements of a numpy array using For loop statement.