+4 votes
in Programming Languages by (19.3k points)

I want to print each element of a 2D NumPy array. I do not want to use two "for" loops. Is there any function to iterate over multi-dimensional NumPy arrays?

1 Answer

0 votes
by (33.7k points)

The Numpy function nditer() is an efficient multi-dimensional iterator. You can use it to iterate over your 2D NumPy arrays.

Here is an example:

>>> import numpy as np
>>> arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> for v in np.nditer(arr):
...     print(v)
...
1
2
3
4
5
6
7
8
 

...