NumPy - Iterating Over Array

Iterating Over Array in NumPy

Iterating over an array in NumPy refers to the process of accessing each element in the array one by one in a systematic manner. This is typically done using loops. Iteration is used to perform operations on each element, such as calculations, modifications, or checks.

NumPy provides several ways to iterate over arrays −

  • Using a for Loop
  • Using ‘nditer()’ Iterator Object
  • Flat Iteration
  • Iteration Order
  • Controlling Iteration Order
  • Broadcasting Iteration
  • Using Vectorized Operations
  • External Loop
  • Modifying Array Values

Using a for Loop

In NumPy, you can use basic Python for loops to iterate over arrays. A for loop is a control flow statement used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). It allows you to execute a block of code repeatedly for each element in the sequence.

Iterating Over One-dimensional Arrays

A 1-dimensional array is basically a list of elements. Iterating over it is simple and similar to iterating over a regular Python list.

Example

In the following example, we create a NumPy array from a list of elements and iterate over each element using a for loop −

import numpy as np

# Create a 1-dimensional NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Iterate over the array
for element in arr:
   print(element)

Following is the output obtained −

1
2
3
4
5

Iterating Over Multi-Dimensional Arrays

NumPy arrays can have any number of dimensions, commonly referred to as axes. For instance −

  • A 1-dimensional array is a list of elements.

  • A 2-dimensional array is like a matrix with rows and columns.

  • A 3-dimensional array can be visualized as a collection of 2D matrices.

Example: Iterating Over a 2D Array

When iterating over a 2D array, each iteration accesses one entire row of the array as shown in the example below −

import numpy as np

# Create a 2D NumPy array (3x3 matrix)
arr_2d = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Iterate over the array
for row in arr_2d:
   print(row)

This will produce the following result −

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

Example: Iterating Over a 3D Array

When iterating over a 3D array, each iteration accesses one entire 2D sub-array (matrix) as shown in the following example −

import numpy as np

# Create a 3D NumPy array (2x2x3)
arr_3d = np.array([[[1, 2, 3],
                    [4, 5, 6]],
                   [[7, 8, 9],
                    [10, 11, 12]]])

# Iterate over the array
for matrix in arr_3d:
   print(matrix)

Following is the output of the above code −

[[1 2 3]
 [4 5 6]]
[[ 7  8  9]
 [10 11 12]]

Iterating Over Elements in Multi-Dimensional Arrays

Iterating over elements in multi-dimensional arrays in NumPy is a way to access each individual element, regardless of the dimension of the array. This process requires nested loops to traverse through each dimension of the array structure.

Example

In this example, we are using nested loops to iterate over each row (i) and column (j) to access and print each element using indexing −

import numpy as np

# Create a 2-dimensional NumPy array
arr_2d = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Iterating over elements in the 2D array
# Iterate over rows
for i in range(arr_2d.shape[0]):   
   # Iterate over columns
   for j in range(arr_2d.shape[1]):  
      print(arr_2d[i, j])

The output obtained is as shown below −

1
2
3
4
5
6
7
8
9

Iterating with Indices

Iterating over NumPy arrays using indices is used to access array elements by their specific positions within each dimension of the array.

In NumPy, arrays are indexed starting from 0 for each dimension. Iterating with indices involves using nested loops to traverse through each dimension of the array and access elements using their specific indices.

This approach allows for more precise control over element access and manipulation compared to simple element iteration.

Example

In the following example, we iterate over each element of the 2D array using nested loops. We access and print each element’s value along with its indices −

import numpy as np

# Create a 2-dimensional NumPy array
arr_2d = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Get the dimensions of the array
rows, cols = arr_2d.shape

# Iterate over the array using indices
for i in range(rows):
   for j in range(cols):
      print(f"Element at ({i}, {j}): {arr_2d[i, j]}")

After executing the above code, we get the following output −

Element at (0, 0): 1
Element at (0, 1): 2
Element at (0, 2): 3
Element at (1, 0): 4
Element at (1, 1): 5
Element at (1, 2): 6
Element at (2, 0): 7
Element at (2, 1): 8
Element at (2, 2): 9

Using ‘nditer’ Iterator Object

The nditer() function in NumPy provides an efficient multidimensional iterator object that can be used to iterate over elements of arrays. It uses Python’s standard iterator interface to visit each element of an array.

Example

In this example, the nditer() function is used to iterate over all elements of the array “arr” in a flattened order, printing each element sequentially −

import numpy as np

# Example array
arr = np.array([[1, 2], [3, 4]])

# Iterate using nditer
for x in np.nditer(arr):
   print(x)

The result produced is as follows −

1234

Flat Iteration

Flat iteration refers to iterating over all elements of a multi-dimensional array as if it were one-dimensional. This approach is useful when you need to process or manipulate every single element in the array without considering its original shape or dimensions explicitly.

Example

In this example, we are creating a 2D NumPy array. We then iterate over this array in a flattened sequence using np.nditer with the ‘buffered’ flag, printing each element sequentially −

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Flat iteration using nditer with 'buffered' flag
print("Iterating over the array:")
for x in np.nditer(arr, flags=['buffered']):
   print(x, end=' ')

We get the output as shown below −

Iterating over the array:
1 2 3 4 5 6 

Iteration Order

Iteration order in NumPy refers to the sequence in which elements of an array are accessed during iteration. By default, NumPy arrays are iterated over in a row-major order, also known as C-style order.

This means that for multi-dimensional arrays, iteration starts from the first dimension (rows), iterating through all elements along the last dimension (columns).

Example

In this example, we iterate over an array using numpy.nditer() function, accessing each element in the default row-major order (C-style), and printing them sequentially −

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Iterate over the array
print("Default Iteration Order (C-style, row-major):")
for x in np.nditer(arr):
   print(x, end=' ')

Following is the output obtained −

Default Iteration Order (C-style, row-major):
1 2 3 4 5 6 

Controlling Iteration Order

Controlling iteration order in NumPy allows you to specify how elements of an array are accessed during iteration. NumPy provides options to control the iteration order based on memory layout and performance considerations −

  • Fortran-style Order − Iterates over elements column-wise (column-major order).

  • for x in np.nditer(arr, order='F'):
        ...
    
  • External Loop − Maintains the inner dimensions intact while iterating over the outer dimensions.

  • for row in np.nditer(arr, flags=['external_loop']):
        ...
    

Example

In this example, we iterate over an array using numpy.nditer() function, accessing each element in the Fortran-style order (F-style) −

import numpy as np

# array
arr = np.array([[1, 2], [3, 4]])

# Iterate in specified order (F-style)
for x in np.nditer(arr, order='F'):
   print(x)

This will produce the following result −

1
3
2
4

Broadcasting Iteration

Broadcasting iteration in NumPy refers to iterating over multiple arrays simultaneously, where the arrays are broadcasted to have compatible shapes.

This allows element-wise operations to be applied efficiently across arrays without explicitly aligning their dimensions.

Example

In the following example, we are demonstrating broadcasting iteration in NumPy by iterating over two arrays, arr1 and arr2, simultaneously.

Each pair of corresponding elements from “arr1” and “arr2” is summed using nditer() function, showing element-wise operations without explicit alignment of array dimensions −

import numpy as np

# arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([10, 20, 30])

# Broadcasting addition operation
print("Broadcasting Iteration:")
for x, y in np.nditer([arr1, arr2]):
   print(x + y, end=' ')

Following is the output of the above code −

Broadcasting Iteration:
11 22 33 

Using Vectorized Operations

Vectorized operations in NumPy refer to performing operations on entire arrays at once, rather than iterating over individual elements.

Example

In the example below, we are demonstrating vectorized operations in NumPy by performing element-wise addition on two arrays, arr1 and arr2. This is achieved simply by using the + operator between the arrays −

import numpy as np

# Example arrays
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([10, 20, 30, 40])

# Vectorized addition operation
result = arr1 + arr2

print("Vectorized Operations:")
print("Result of addition:", result)

The output obtained is as shown below −

Vectorized Operations:Result of addition: [11 22 33 44]

External Loop

In NumPy, the concept of an external loop refers to iterating over arrays while maintaining certain dimensions intact. This allows you to iterate over arrays with nested structures, without collapsing the inner dimensions into a single sequence.

The numpy.nditer() function, when used with the external_loop flag, allows iterating through array elements while preserving the array’s row structure. This ensures that each row is processed individually, demonstrating how the integrity of dimensions is maintained throughout the iteration process.

Example

In the following example, we are illustrating external loop iteration in NumPy by iterating over a 2D array −

import numpy as np

# array with multiple dimensions
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# External loop iteration
print("External Loop:")
for row in np.nditer(arr, flags=['external_loop']):
   print(row)

After executing the above code, we get the following output −

External Loop:[1 2 3 4 5 6]

Modifying Array Values

Modifying array values in NumPy is used to directly assign new values to specific elements or slices within an array. This helps in updating data in-place without needing to recreate the entire array.

The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.

Example

In the example below, we are modifying the array values in NumPy using the nditer() function. By setting the “op_flags” parameter to ‘readwrite’, the iterator multiplies each element of the array arr by 2 −

import numpy as np

# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])

# Modify array elements
with np.nditer(arr, flags=['buffered'], op_flags=['readwrite']) as it:
   for x in it:
      # Multiply each element by 2
      x[...] = x * 2  

print("Modified Array Example:",arr)

The result produced is as follows −

Modified Array Example: [ 2  4  6  8 10]
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team