Numpy ndarray.flat Attribute
The Numpy ndarray.flat Attribute which returns a 1-D iterator over the array. This iterator allows us to iterate over the array as if it were flattened but it does not create a new array.
This Attribute is especially useful when we need to iterate over elements of a multidimensional array in a flat manner.
Syntax
Here is the syntax of Numpy ndarray.flat() Attribute −
numpy.ndarray.flat
Parameter
The Numpy ndarray.flat attribute does not take any parameters.
Return Value
This attribute returns a 1-D iterator over the array. This iterator can be used to access and modify elements of the array.
Example 1
Following is the example of Numpy ndarray.flat Attribute, which shows how to iterate over each element of a 2D array using flat Attribute −
import numpy as np
# Creating a 2D numpy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Using flat to iterate over elements
for item in array_2d.flat:
print(item)
Output
1 2 3 4 5 6
Example 2
This example doubles each element in the array by iterating through the flat iterator and modifying each element.
import numpy as np
# Creating a 2D numpy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Modifying elements using flat iterator
for index, value in enumerate(array_2d.flat):
array_2d.flat[index] = value * 2
print(array_2d)
After execution of above code, we get the following result
[[ 2 4 6] [ 8 10 12]]
Example 3
Here in this example we access specific elements of a 3D array using the flat iterator, showing how the flat iterator flattens the multidimensional array into a single dimension for easy access −
import numpy as np # Creating a 3D numpy array array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Accessing specific elements using flat print(array_3d.flat[0]) # First element print(array_3d.flat[5]) # Sixth element print(array_3d.flat[-1]) # Last element
Output
1 6 8