NumPy Array Iteration

In NumPy, iteration means accessing array elements one by one using loops. It allows you to read, process, and perform operations on array elements. NumPy supports iteration over 1-D, 2-D, and multi-dimensional arrays using simple Python loops and the nditer() function.

1. What is Array Iteration in NumPy?

Array iteration means accessing each element of an array one at a time.

You can use a for loop to iterate through a NumPy array.

Example:

import numpy as np

arr = np.array([10, 20, 30, 40])

for x in arr:
    print(x)

Output:

10
20
30
40

Explanation:

  • The for loop accesses each element of the array.
  • The variable x stores one element at a time.
  • The loop continues until all elements are accessed.

2. Iterating Through a 1-D Array

A 1-D array contains elements in a single dimension. You can directly use a for loop to access each element.

Example:

import numpy as np

marks = np.array([75, 80, 85, 90, 95])

for mark in marks:
    print("Student Marks:", mark)

Output:

Student Marks: 75
Student Marks: 80
Student Marks: 85
Student Marks: 90
Student Marks: 95

Explanation:

The loop reads each student’s marks one by one and prints the value.

3. Iterating Through a 2-D Array

A 2-D array contains rows and columns. When you use a simple for loop, NumPy returns one row at a time.

Example:

import numpy as np

arr = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

for row in arr:
    print(row)

Output:

[10 20 30]
[40 50 60]

Explanation:

  • The first iteration returns the first row.
  • The second iteration returns the second row.
  • Each row is returned as a NumPy array.

4. Iterating Through Each Element of a 2-D Array

If you want to access every element individually, you can use a nested for loop.

Example:

import numpy as np

arr = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

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

Output:

10
20
30
40
50
60

Explanation:

  • The outer loop accesses one row at a time.
  • The inner loop accesses each element of that row.
  • Every element is printed individually.

5. Iterating Through a 3-D Array

A 3-D array contains multiple 2-D arrays. You can use nested loops to access its elements.

Example:

import numpy as np

arr = np.array([
    [
        [10, 20, 30],
        [40, 50, 60]
    ],
    [
        [70, 80, 90],
        [100, 110, 120]
    ]
])

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

Output:

10
20
30
40
50
60
70
80
90
100
110
120

Explanation:

  • The first loop accesses each 2-D group.
  • The second loop accesses each row.
  • The third loop accesses individual elements.

6. Iterating Through an Array Using nditer()

NumPy provides the nditer() function to iterate through elements of an array without writing multiple nested loops.

It works with arrays of different dimensions.

Example:

import numpy as np

arr = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

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

Output:

10
20
30
40
50
60

Explanation:

  • np.nditer(arr) creates an iterator for the array.
  • It accesses every element individually.
  • You do not need separate loops for rows and columns.

7. Iterating Through an Array Using ndenumerate()

The ndenumerate() function returns both the index and value of each array element.

It is useful when you need to know the position of an element during iteration.

Example:

import numpy as np

arr = np.array([10, 20, 30, 40])

for index, value in np.ndenumerate(arr):
    print("Index:", index, "Value:", value)

Output:

Index: (0,) Value: 10
Index: (1,) Value: 20
Index: (2,) Value: 30
Index: (3,) Value: 40

Explanation:

  • index stores the position of the element as a tuple.
  • value stores the actual element.
  • For a 1-D array, each index is represented as (0,), (1,), and so on.

8. Iterating Through a 2-D Array Using ndenumerate()

You can also use ndenumerate() with a 2-D array. It returns the row and column positions along with each value.

Example:

import numpy as np

arr = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

for index, value in np.ndenumerate(arr):
    print("Index:", index, "Value:", value)

Output:

Index: (0, 0) Value: 10
Index: (0, 1) Value: 20
Index: (0, 2) Value: 30
Index: (1, 0) Value: 40
Index: (1, 1) Value: 50
Index: (1, 2) Value: 60

Explanation:

  • The first value in the index represents the row.
  • The second value represents the column.
  • Each element is accessed along with its position.

9. Difference Between for Loop, nditer(), and ndenumerate()

NumPy provides different ways to iterate through arrays.

MethodPurpose
for loopAccesses array elements or rows
Nested for loopAccesses individual elements in multi-dimensional arrays
nditer()Iterates through every element without nested loops
ndenumerate()Returns each element along with its index

Student Task

A teacher stores the marks of five students in a NumPy array.

import numpy as np

marks = np.array([75, 80, 65, 90, 85])

Complete these tasks:

  1. Print each student’s marks using a for loop.
  2. Print only marks greater than 75 using a loop and an if condition.
  3. Display each mark along with its index using ndenumerate().
  4. Calculate the total marks using a loop.
  5. Display all marks using nditer().

Final Student Challenge: Company Sales Records

A company stores monthly sales figures for its employees across two departments.

import numpy as np

sales = np.array([
    [
        [10000, 12000, 15000],
        [18000, 20000, 22000]
    ],
    [
        [13000, 16000, 19000],
        [21000, 24000, 27000]
    ]
])

# Iterate through every sales value
print("All Sales Records:")

for value in np.nditer(sales):
    print(value)

# Display each value with its index
print("\nSales Values with Index:")

for index, value in np.ndenumerate(sales):
    print("Index:", index, "Sales:", value)

Expected Output:

All Sales Records:
10000
12000
15000
18000
20000
22000
13000
16000
19000
21000
24000
27000

Sales Values with Index:
Index: (0, 0, 0) Sales: 10000
Index: (0, 0, 1) Sales: 12000
Index: (0, 0, 2) Sales: 15000
Index: (0, 1, 0) Sales: 18000
Index: (0, 1, 1) Sales: 20000
Index: (0, 1, 2) Sales: 22000
Index: (1, 0, 0) Sales: 13000
Index: (1, 0, 1) Sales: 16000
Index: (1, 0, 2) Sales: 19000
Index: (1, 1, 0) Sales: 21000
Index: (1, 1, 1) Sales: 24000
Index: (1, 1, 2) Sales: 27000

Your Challenge:

  1. Print all sales values using nditer().
  2. Display each sales value with its index using ndenumerate().
  3. Print only sales values greater than 20,000 using a for loop and an if condition.
  4. Count how many sales entries are greater than 15,000.
  5. Calculate the total sales using a loop.

Key Takeaways

  • Python array Iteration means accessing array elements one by one.
  • A for loop can access elements of a 1-D array directly.
  • Nested loops are useful for accessing individual elements in 2-D and 3-D NumPy array.
  • nditer() provides a simple way to NumPy iteration through every element.
  • ndenumerate() returns both the index and value of each element.
  • You can use loops to filter, count, and calculate array values.

Frequently Asked Questions (FAQs)

1. What is NumPy Array Iteration in Python?

NumPy Array Iteration is the process of accessing and processing each element of a NumPy Array one by one. It allows you to perform operations on array elements using loops and other iteration techniques.

2. How do you iterate through a NumPy Array using a for loop?

You can use a Python for loop to iterate through each element of a NumPy Array.

Example:

import numpy as np

arr = np.array([10, 20, 30, 40])

for x in arr:
    print(x)

3. What is the difference between NumPy Iteration and Python Array Iteration?

Python Array Iteration generally uses loops to access elements one by one. NumPy Iteration also supports multidimensional arrays, allowing you to access elements row by row or across different dimensions.

4. How do you iterate through a 2-D NumPy Array?

You can use nested for loops to iterate through a 2-D NumPy Array. The outer loop accesses rows, while the inner loop accesses individual elements within each row.

5. How do you iterate through a 3-D NumPy Array?

You can use three nested for loops to iterate through a 3-D NumPy Array. Each loop accesses a different level of the array: the outermost loop accesses blocks, the second loop accesses rows, and the innermost loop accesses individual elements.

6. What is the np.nditer() function in NumPy?

The np.nditer() function provides an efficient way to iterate through every element of a NumPy Array, regardless of its number of dimensions.

Example:

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

7. Can we use a single for loop to iterate through a multidimensional NumPy Array?

Yes, you can use a single for loop with np.nditer() to access every element of a multidimensional NumPy Array without writing nested loops.

8. Why is NumPy Array Iteration important in Python?

NumPy Array Iteration is useful for accessing, processing, and performing operations on array elements. It is commonly used in data analysis, scientific computing, mathematical calculations, and machine learning.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top