NumPy Array Iterating

Iterating walks through every element of a NumPy array, and the right technique depends on how many dimensions you are working with.

Iterating Arrays

Iterating means going through elements one by one. For a 1-D array a simple for loop is enough, but as dimensions increase, a plain for loop starts returning whole sub-arrays instead of individual scalar values, so you either need nested loops or NumPy's dedicated iteration helper, nditer().

Iterating 1-D Arrays

Example

import numpy as np

arr = np.array([1, 2, 3])

for x in arr:
    print(x)

# Output:
# 1
# 2
# 3

Iterating 2-D and 3-D Arrays

A for loop over a 2-D array yields each row as a 1-D array, not each individual number. To reach the scalar values you need one nested loop per extra dimension: one loop for a 2-D array, two nested loops for a 3-D array, and so on.

Example

import numpy as np

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

for row in arr:
    for x in row:
        print(x)

# Output:
# 1
# 2
# 3
# 4
# 5
# 6

Iterating With nditer()

Writing a nested loop for every dimension gets tedious fast, especially for arrays with many axes. np.nditer() flattens that complexity: it visits every scalar element in the array regardless of how many dimensions it has, using a single loop.

Example

import numpy as np

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

for x in np.nditer(arr):
    print(x)

# Output:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
Note: nditer() also accepts an op_dtypes argument so you can iterate as if the array were cast to another type, for example np.nditer(arr, flags=['buffered'], op_dtypes=['S']). When you need the index of each element too, use np.ndenumerate(arr) instead, which yields (index_tuple, value) pairs.
ApproachBest For
Plain for loop1-D arrays only
Nested for loopsSmall, fixed number of dimensions
np.nditer()Any number of dimensions, values only
np.ndenumerate()Any number of dimensions, when you need indices too

Exercise: NumPy Array Iterating

When you use a basic for loop on a 2D NumPy array, what do you get on each iteration?