Skip to main content

NumPy: Iterating Over Arrays

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
Submitted by devanshi.srivastava on September 1, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.