/    /  NumPy – Iterating Over Array

NumPy – Iterating Over Array:

In this tutorial, we will learn about array iteration in Numpy.
In python, we have used iteration through lists. In the same way, we can iterate over arrays in Numpy.
Let us see an example by giving an array of integer elements.
Example:
>>> a=np.array([1,2,3,4,5,6,7,8,9,10],int)
# print the array a.
>>> a
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
# iterate over the array a of integer numbers.
>>> for i in a:
print (i)
# Below is the Output:
1
2
3
4
5
6
7
8
9
10
How this works with Multidimensional array ?
Here the iteration will go over the first axis so that each loop returns you the subset of the array.
Let us try with 2 – Dimensional Array.
Example:
# 2-D Array
>>> a=np.array([[1,2],[3,4],[5,6],[7,8],[9,10]],int)
# Print the 2-D Array
>>> a
array([[ 1,  2],
[ 3,  4],
[ 5,  6],
[ 7,  8],
[ 9, 10]])
# Iterating Through 2-D Array
>>> for i in a:
print (i)
[1 2]
[3 4]
[5 6]
[7 8]
[ 9 10]
# Doing the calculation along with the array iteration.
>>> for (i,j) in a:
print (i+j)
3
7
11
15
19
Let us work with the 3-Dimensional Array.
# 3-Dimensional Array
>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]],int)
# Print 3-Dimensional Array
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Iterating Through 3-Dimensional Array
>>> for i in a:
print (i)
[1 2 3]
[4 5 6]
[7 8 9]
# Doing the calculation along with the array iteration.
>>> for (x,y,z) in a:
print (x+y+z)
6
15
24
>>> for (x,y,z) in a:
print (x*y*z)
6
120
504