Iterate over Elements of Array – NumPy

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.


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=' ')
Run Code Copy


Iterate over Elements of Array – NumPy


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

Related Tutorials

Code copied to clipboard successfully 👍