NumPy ndarray.flat

The numpy.ndarray.flat attribute returns a 1-D iterator over the elements of a NumPy array, allowing element-wise iteration in a flattened manner.

Syntax

</>
Copy
ndarray.flat

Return Value

Returns a numpy.flatiter object, which is an iterator that enables iteration over a multi-dimensional array as if it were 1-D.


Examples

1. Iterating Over Elements Using ndarray.flat

We create a 2D array and use flat to iterate through its elements as if it were a 1D array.

</>
Copy
import numpy as np

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

# Using the flat attribute to iterate through all elements
for element in arr.flat:
    print(element)

Output:

1
2
3
4
5
6

Although the original array is 2D, flat allows us to iterate over it as if it were a 1D array.

2. Accessing Elements Using Indices with ndarray.flat

The flat iterator allows direct indexing to access elements in a flattened array.

</>
Copy
import numpy as np

# Creating a 3x3 NumPy array
arr = np.array([[10, 20, 30], 
                [40, 50, 60], 
                [70, 80, 90]])

# Accessing elements using flat iterator
print(arr.flat[0])  # First element (10)
print(arr.flat[4])  # Fifth element (50)
print(arr.flat[-1]) # Last element (90)

Output:

10
50
90

Using indices, we can access elements in a flattened view of the array, even if it has multiple dimensions.

3. Modifying Elements Using ndarray.flat

We can also use flat to modify elements directly in the original array.

</>
Copy
import numpy as np

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

# Modifying elements using flat
arr.flat[1] = 99   # Changing second element
arr.flat[-1] = 88  # Changing last element

print(arr)

Output:

[[ 1 99  3]
 [ 4  5 88]]

Even though we modify elements using flat (as if the array were 1D), the changes reflect in the original multi-dimensional structure.

4. Using ndarray.flat in Slicing

We can assign values to multiple elements at once using slicing in flat.

</>
Copy
import numpy as np

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

# Assigning values using flat slicing
arr.flat[1:4] = [99, 77, 55]  # Modify elements at indices 1, 2, and 3

print(arr)

Output:

[[ 1 99 77]
 [55  5  6]]

Using slicing, we update multiple elements efficiently in a multi-dimensional array through a flattened view.