For loop on python is used to repeat a certain action over a given course of time. The for loop iterates through the data and executes the block each time. In this article, you will get to know how to create for loop Numpy array in Python programming language.

A simple for loop Numpy array in python

In this section, we are going to create for loop Numpy array in python. Let’s see how it works.

import numpy as np 
test_array = np.array([3,2,1])

for x in test_array:
    print(x)
3
2
1

well, you can see here that the for loop will iterate over the data prints the required ones.

For loop using 2D array in Python

For this purpose let’s create a 2D Numpy array in our working environment.

import numpy as np 
test_array = np.array([[3,2,1],[1,2,3]])

for x in test_array:
    print(x)
[3 2 1]
[1 2 3]

We have created a 2D Numpy array. Now, let’s create a for loop which iterates over the data and prints the required ones. The above output shows the working of for loop over a 2D Bumpy array as well.

For loop using 3 array in Python

Till now, we have created 1D and 2D arrays, but in this section we are going to create a 3D array and will create for loops to iterate over the data.

Let’s see how it works.

import numpy as np 
test_array = np.array([[[3,2,1],[1,2,3]],[[5,6,7],[10,9,8]]])

for x in test_array:
    print(x)

[[3 2 1]
 [1 2 3]]
[[ 5  6  7]
 [10  9  8]]

You can observe that the for loop will iterate over the data and prints the required or specified values.

Using the for loop you can easily iterate over any array and prints the elements in it.

Wrapping Up

For loops are the popular looping concepts in programming. You can use for loop to iterate over the given array and then prints the specified data from that array.

The different types of the looping concepts were explained in the previous articles. You can use different loops based on the given conditions. I hope by now you got better of for loop Numpy array.

That’s all for now. Happy looping!!!

More read: Numpy Docs

Categorized in:

Tagged in: