Get Started

Loop over NumPy array

If you're dealing with a 1D NumPy array, looping over all elements can be as simple as:

for x in my_array :
    ...

If you're dealing with a 2D NumPy array, it's more complicated. A 2D array is built up of multiple 1D arrays. To explicitly iterate over all separate elements of a multi-dimensional array, you'll need this syntax:

for x in np.nditer(my_array) :
    ...

Two NumPy arrays that you might recognize from the intro course are available in your Python session: np_height, a NumPy array containing the heights of Major League Baseball players, and np_baseball, a 2D NumPy array that contains both the heights (first column) and weights (second column) of those players.

This is a part of the course

“Intermediate Python”

View Course

Exercise instructions

  • Import the numpy package under the local alias np.
  • Write a for loop that iterates over all elements in np_height and prints out "x inches" for each element, where x is the value in the array.
  • Write a for loop that visits every element of the np_baseball array and prints it out.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import numpy as np


# For loop over np_height


# For loop over np_baseball

This exercise is part of the course

Intermediate Python

BeginnerSkill Level
4.6+
772 reviews

Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

There are several techniques you can use to repeatedly execute Python code. While loops are like repeated if statements, the for loop iterates over all kinds of data structures. Learn all about them in this chapter.

Exercise 1: while loopExercise 2: while: warming upExercise 3: Basic while loopExercise 4: Add conditionalsExercise 5: for loopExercise 6: Loop over a listExercise 7: Indexes and values (1)Exercise 8: Indexes and values (2)Exercise 9: Loop over list of listsExercise 10: Loop Data Structures Part 1Exercise 11: Loop over dictionaryExercise 12: Loop over NumPy array
Exercise 13: Loop Data Structures Part 2Exercise 14: Loop over DataFrame (1)Exercise 15: Loop over DataFrame (2)Exercise 16: Add column (1)Exercise 17: Add column (2)

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free