NumPy: Iterating Over Arrays

Profile picture for user devanshi.srivastava
Submitted by devanshi.srivastava on

In Python, Iterating means going through elements present in an array one by one. By using basic for and while loop of python we can iterate one-dimensional and two-dimensional array.

Example:

Using for loop:

#Iterations using for loop
import numpy as np

array_0= np.array([[1,2,3],[4,5,6]])

for x in array_0:
    for y in x:
        print(y)
    print() 

Output:

1
2
3

4
5
6

Using while loop:

#Iterations using while loop
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
i = 0
j = 0
rows, cols = x.shape
while i < rows:
    j = 0
    while j < cols:
        print(x[i][j])
        j = j + 1
    print()
    i = i + 1

Output:

1
2
3

4
5
6