Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

NumPy Accessing Array Elements (Iteration)

In this tutorial, we will learn how to iterate over any given array to one by one access all the available elements in the array (array iteration) in the NumPy library.

The numpy.nditer is an iterator object provided by the Numpy library.

  • numpy.nditer is an efficient multidimensional iterator object that is used to iterate over an array in the Numpy library.

  • With the help of this iterator object, each element of the given array is visited using Python Iterator interface.

Example 1

Let us take a look at an example where we will create an ndarray using the arange() method and then iterate over it using numpy.nditer:

import numpy as np

a = np.arange(0,40,5)

print ("The Original array is:")
print (a)
print ('\n')

# showing elements of array one by one
print ("The Modified array is:")
for x in np.nditer(a):
    print(x)

Output of the above code will be:

numpy ndarray iteration example

Note: It is important to note here that the order of the iteration doesn't follow any special ordering like row-major or column-order, however the order of iteration is always chosen to match the memory layout of the given array. You can check it just by iterating over the transpose of the array.

Example 2: Iterate over Transpose of array

Let us take an example where we will take an array, then we will see the transpose of the given matrix and we will iterate using nditer. The code for the same is as follows:

import numpy as np  

a = np.array([[11,2,3,4],[29,4,15,6],[11,21,39,31]])  
print("The array is :")  
print(a)  

print("The transpose of the array is :")  
at = a.T 
 
print(at)  
print("Iterating over the array:")   
for x in np.nditer(at):  
    print(x, end=' ')  

Output of the above code will be:

iterate over transpose of ndarray

Order of Iteration in Numpy

In Numpy, basically we have two ways with the help of which we can store elements into an array and these are as follows:

order of array iteration in Numpy

Now we will cover example of how the numpy Iterator treats the specific orders (F-style or C-style).

Example 3: Iterate over F-style and -style Order array

Below we have an example where we will iterate in F-style and C-style both. The code snippet for the same is as follows:

import numpy as np  

a = np.array([[1,2,3,4],[8,9,5,6],[10,20,29,31]])  
print("\nPrinting the array:\n")  
print(a)  
print("\nPrinting the transpose of the array:\n")  
at = a.T  
print(at)  
print("\nIterating over the transposed array\n")  
  
for x in np.nditer(at):  
    print(x, end= ' ')  
print("\nSorting the transposed array in C-style:\n")  
c = at.copy(order = 'C')  
print(c)  
  
print("\nIterating over the C-style array:\n")  
for x in np.nditer(c):  
    print(x, end=' ')  
      
d = at.copy(order = 'F')  
print("\n")
print(d) 

print("\nIterating over the F-style array:\n")  
for x in np.nditer(d):  
    print(x, end=' ')  


Printing the array:

[[ 1 2 3 4]
[ 8 9 5 6]
[10 20 29 31]]

Printing the transpose of the array:

[[ 1 8 10]
[ 2 9 20]
[ 3 5 29]
[ 4 6 31]]

Iterating over the transposed array

1 2 3 4 8 9 5 6 10 20 29 31
Sorting the transposed array in C-style:

[[ 1 8 10]
[ 2 9 20]
[ 3 5 29]
[ 4 6 31]]

Iterating over the C-style array:

1 8 10 2 9 20 3 5 29 4 6 31

[[ 1 8 10]
[ 2 9 20]
[ 3 5 29]
[ 4 6 31]]

Iterating over the F-style array:

1 2 3 4 8 9 5 6 10 20 29 31

Important Point to Note:

It is important to note that you can mention the order 'C' or 'F' at the time of defining the Iterator object itself.

Let us cover an example where we will mention the order while defining the iterator object:

import numpy as np  
  
a = np.array([[1,2,3,4],[8,9,5,6],[10,20,29,31]])    
print("\n The array:\n")  
print(a)  
print("\n The transpose of the array is :\n")  
at = a.T  
print(at)  
print("\nIterating over the transposed array\n")  
for x in np.nditer(at):  
    print(x, end= ' ')  

print("\nIterating over transposed array in C-style order:\n")  
for x in np.nditer(at, order = 'C'):  
    print(x,end=' ')  

Output of the above code will be:

numpy array iteration example

Numpy Array Broadcasting Iteration

In case if two arrays are broadcastable then a combined nditer object is able to iterate upon them concurrently. Assuming that an array x has dimension 3x4, and there is another array y of dimension 1x4, then we use the broadcasting iterator (array b is broadcast to size of a).

The code example for the same is as follows:

import numpy as np 

a = np.arange(0,60,5) 
a = a.reshape(3,4) 

print ('The First array :') 
print (a)
print ('\n')

print ('The Second array is') 
b = np.array([1, 2, 3, 4], dtype = int) 
print (b)  
print ('\n' )

print ('The Modified array is') 
for x,y in np.nditer([a,b]): 
    print ("%d:%d" %(x,y))

numpy ndarray broadcasting iteration example

Modifying the values of an Array

Another optional parameter of the nditer object is called as op_flags. The default value of this parameter is read-only but it can also be set to read-write or write-only mode. With the help of this, you are able to easily modify the values of all or some of the elements in the array using this iterator.

Let us take a look at the example for the same:

import numpy as np

a = np.arange(0,50,6)
a = a.reshape(3,3)
print ('The Original array is:')
print (a)
print ('\n')
for x in np.nditer(a, op_flags = ['readwrite']):
    # modifying the value of array elements
    x[...] = 2+x
print ('The Modified array is:')
print (a)


The Original array is:
[[ 0 6 12]
[18 24 30]
[36 42 48]]


The Modified array is:
[[ 2 8 14]
[20 26 32]
[38 44 50]]

Summary

In this tutorial, we have covered the nditer object in Numpy which is used for the iteration over the arrays. After that, we have covered how the order of iteration plays a role in iteration with the help of an example. Then learned the Broadcasting Iteration along with its example. And finally we covered how to modify the values of array at the time of iteration.