VOOZH about

URL: https://www.geeksforgeeks.org/python/numpy-iterating-over-array/

⇱ Numpy - Iterating Over Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numpy - Iterating Over Arrays

Last Updated : 23 Jul, 2025

NumPy provides flexible and efficient ways to iterate over arrays of any dimensionality. For a one-dimensional array, iterating is straightforward and similar to iterating over a Python list.

Let's understand with the help of an example:


Output
1
2
3
4
5

Explanation:

  • Each element of the array is accessed sequentially, making iteration simple and intuitive.

Let's explore various others ways to iterate over Arrays:

Iteration Over a Two-Dimensional Array

For multidimensional arrays, iteration is performed over the first axis by default. Each iteration yields a one-dimensional sub-array.


Output
[1 2 3]
[4 5 6]
[7 8 9]

Explanation:

  • arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) creates a 2D array with three rows and three columns.
  • for row in arr_2d: loops through each row of the 2D array, treating it as a separate one-dimensional array.

For Element-Wise Iteration

To iterate over individual elements of a 2D array, the array can be flattened using the .flat attribute.


Output
1
2
3
4
5
6
7
8
9

Iterating Over Higher-Dimensional Arrays

Iteration is similar for arrays with more than two dimensions. In such cases, iteration occurs along the first axis by default.


Output
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]

Explanation:

  • Each iteration returns a 2D sub-array from the 3D array.

Using nditer

The numpy.nditer object offers a various way to iterate over arrays. It allows iteration in different orders and provides better control over the iteration process.


Output
1
2
3
4

We can also specify the order of iteration (row-major order 'C' or column-major order 'F'):


Output
1
3
2
4

Using Enumerate

For multidimensional arrays, we can use enumerate to access both the index and value during iteration.


Output
Row 0: [10 20]
Row 1: [30 40]

Using Broadcasting

When working with arrays of different shapes, Broadcasting allows iteration across combined shapes seamlessly.


Output
1 + 10 = 11
2 + 10 = 12
3 + 10 = 13
1 + 20 = 21
2 + 20 = 22
3 + 20 = 23
Comment
Article Tags:
Article Tags: