Member-only story
Hi everyone, welcome back. NumPy is a library for the Python programming language. NumPy is short for “Numerical Python” and is a popular library that is used in data science. NumPy is used specifically to work with arrays as it provides various functions and support. In this tutorial, we will be going over how to iterate through a NumPy array. With this introduction out of the way, let’s get into it.
Examples Using a For Loop
Let’s look at some examples of how to iterate through an array using a for loop:
import numpy as np
array = np.array([1, 2, 3, 4, 5, 6])
for x in array:
print(x)Output:
1
2
3
4
5
6
In the example above, we created a 1-D array and have successfully looped though each individual value. Now let’s look at an example of us looping through a 2-D array:
import numpy as np
array = np.array([[1, 2, 3], [4, 5, 6]])
for x in array:
for y in x:
print(y)Output:
1
2
3
4
5
6
As we can see in the output above, we are still able to print out each individual value. Because it is a 2-D array, we have to use a nested for loop to retrieve each individual value. This is how we may normally iterate through arrays, but NumPy provides us with new functions…