Iterating Over Array

Numpy package contains an iterator object Numpy.nditer. It is an efficient multi-dimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface. The iterator object nditer, introduced in Numpy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.
Single array iteration: The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.
Single Array Iteration using nditer
import numpy as np

a = np.arange(6).reshape(2,3)
for x in np.nditer(a):
     print (x,end=",")

Controlling iteration order

There are times when it is important to visit the elements of an array in a specific order, irrespective of the layout of the elements in memory. The nditer object provides an order parameter to control this aspect of iteration.

## Here order doesn't matter
a = np.arange(6).reshape(2,3)
for x in np.nditer(a, order='F'):
     print (x,end=",")

Leave a Comment

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