What is the numpy.ndarray.flat attribute in Python?

Overview

The ndarray.flat attribute in Python is used to return a 1-D iterator over a given input array by using the index number of each of the array elements.

Syntax

ndarray.flat
Syntax for the ndarray.flat attribute

Parameter value

The ndarray.flat attribute takes no parameter values since it is an attribute. It only goes with the index number of the element of the array in a square bracket, [ ].

Return value

The ndarray.flat attribute returns a 1-D iterator over the input array.

Example

import numpy as np
# creating an input array
myarray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# getting the ndarray.flat attribute of the elementi in index 5
print(myarray.flat[5])

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array of values, myarray , using the array() function.
  • Line 6: We obtain and print the attribute (element) of the array in index 5 using the ndarray.flat attribute.

Free Resources