TExcelTAD
Home › NumPy › NumPy Array Iterating

NumPy Array Iterating

Iterating means visiting elements one by one with a for loop. A plain loop over an array walks along its first axis: for a 1-D array you get elements, for a 2-D array you get rows.

python · try it yourself
import numpy as np

steps = np.array([4200, 8100, 6500])
for s in steps:
    print(s)

week = np.array([[1, 2, 3],
                 [4, 5, 6]])
for row in week:
    print("row:", row)
4200
8100
6500
row: [1 2 3]
row: [4 5 6]

To reach individual values of a 2-D array with plain loops you nest one loop per dimension:

python · try it yourself
import numpy as np

week = np.array([[1, 2, 3],
                 [4, 5, 6]])
for row in week:
    for value in row:
        print(value, end=" ")
print()
1 2 3 4 5 6

That gets tedious for 3-D or 4-D data. NumPy has better tools.

np.nditer: every element, any dimension

np.nditer(a) yields each element in turn, no matter how many dimensions a has:

python · try it yourself
import numpy as np

cube = np.arange(8).reshape(2, 2, 2)
for x in np.nditer(cube):
    print(x, end=" ")
print()
0 1 2 3 4 5 6 7

nditer has options for advanced use. Two helpful ones: op_dtypes with flags=["buffered"] converts on the fly, and slicing the input lets you skip elements:

python · try it yourself
import numpy as np

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

# Every second column, viewed as floats
for x in np.nditer(a[:, ::2], flags=["buffered"], op_dtypes=["float64"]):
    print(x, end=" ")
print()
1.0 3.0 5.0 7.0

Knowing where you are: np.ndenumerate

Python's enumerate gives a counter; NumPy's np.ndenumerate gives the full index tuple of each element:

python · try it yourself
import numpy as np

# Free seats in a tiny cinema: 1 = free
seats = np.array([[0, 1, 0],
                  [1, 1, 0]])
for (row, col), free in np.ndenumerate(seats):
    if free:
        print(f"Row {row}, seat {col} is free")
Row 0, seat 1 is free
Row 1, seat 0 is free
Row 1, seat 1 is free

Iterating over columns

Looping over a.T (the transpose) visits the columns, because the transpose turns columns into rows:

python · try it yourself
import numpy as np

scores = np.array([[70, 80, 90],
                   [60, 75, 95]])
for i, column in enumerate(scores.T):
    print(f"test {i}: {column}, best {column.max()}")
test 0: [70 60], best 70
test 1: [80 75], best 80
test 2: [90 95], best 95

Should you iterate at all?

Loops in Python run one element at a time in the interpreter, which is far slower than NumPy's built-in operations. Most of the time you can replace a loop with a vectorised expression:

Loop version Vectorised version
[x * 2 for x in a] a * 2
sum(x for x in a if x > 0) a[a > 0].sum()
loop that tracks max per column a.max(axis=0)

Tip: Use loops for small arrays, for printing, or when each step depends on the previous one. For calculations on whole arrays, reach for vectorised operations first. The Performance and Vectorization lesson measures the difference.

Test yourself

What does for x in a: yield when a is 2-D?

  1. Individual elements
  2. Rows
  3. Columns
  4. Index tuples

Which function yields (index_tuple, value) pairs?

  1. np.nditer
  2. np.ndenumerate
  3. enumerate
  4. np.ndindex

How can you loop over the columns of a 2-D array a?

  1. for c in a:
  2. for c in a.T:
  3. for c in a.flat:
  4. for c in a.shape: