NumPy ndarray.flat Attribute



The NumPy ndarray.flat attribute provides a flat iterator over a NumPy array. It returns a 1-dimensional iterator that can be used to iterate over each element of the array in a flattened manner, regardless of the original shape of the array.

It is useful when you need to iterate over the elements of an array in a sequential manner without worrying about the array's shape or dimensionality.

The flat attribute does not change the array but allows for a simpler, linear iteration of its elements.

Usage of the flat Attribute in NumPy

The flat attribute can be accessed directly from a NumPy array to create a flat iterator over the array.

This attribute is helpful when performing element-wise operations or when you need to access elements in a simple, linear order.

Below are some examples that demonstrate how flat can be used to iterate over the elements of an array.

Example: Iterating Over a 2D Array

In this example, we create a 2D array and use the flat attribute to iterate over each element in a flattened manner −

import numpy as np

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

# Iterating over the flattened array
for element in arr.flat:
   print(element)

Following is the output obtained −

1
2
3
4
5
6

Example: Modifying Elements

In this example, we create a 2D array and use the flat attribute to modify its elements. We double each element by iterating over them in a flattened manner −

import numpy as np

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

# Modifying elements by doubling them
for i in arr.flat:
   i *= 2
print(arr)

This will produce the following result −

[[1 2]
 [3 4]]

Example: Flattening a Higher Dimensional Array

In this example, we create a 3-dimensional array and use the flat attribute to iterate over the flattened array −

import numpy as np

# Creating a 3-dimensional array
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

# Iterating over the flattened array
for element in arr.flat:
   print(element)

Following is the output of the above code −

1
2
3
4
5
6
7
8

Example: Using flat with an Empty Array

In this example, we check the result of accessing the flat attribute on an empty array −

import numpy as np

# Creating an empty array
arr = np.array([])

# Iterating over the flattened empty array
for element in arr.flat:
   print(element)

The result produced is as follows −

(no output, as the array is empty)
numpy_array_attributes.htm
Advertisements