+3 votes
in Programming Languages by (73.8k points)

I want to iterate over all elements of a 2D Numpy array. How can I do it without two for loops?

E.g.

>>> aa

array([[1, 2, 3],

       [4, 5, 6],

       [7, 8, 9]])

>>> for e in aa:

...     print(e)

The above code prints the following:

[1 2 3]

[4 5 6]

[7 8 9]

But I want the following output:
1
2
3
4
5
6
7
8
9

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use the flat attribute. It is an iterator over all the elements of the array. This way you do not have to explicitly use two "for" loops.

Here is an example:

>>> import numpy as np
>>> aa=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> aa
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> for e in aa.flat:
...     print(e)
...
1
2
3
4
5
6
7
8
9


...