Python:NumPy flat

Anonymous contributor's avatar
Anonymous contributor
Published Jan 30, 2026
Contribute to Docs

The flat attribute returns a 1-D iterator over all elements of an ndarray, allowing access to each element as if the array were a single flat list. This is useful for loops where the dimensionality or shape of the array is irrelevant and every element needs to be processed in linear order. Iteration follows standard C-style (row-major) ordering.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

The flat attribute is accessed directly on the NumPy array object:

array.flat

Parameters:

The attribute takes no parameters.

Return value:

Returns an object of type numpy.flatiter, which provides efficient, one-dimensional traversal of the array data.

Example

This example demonstrates how to use flat to iterate through every element of a 2x3 array without needing nested loops:

import numpy as np
# Create a 2x3 array
multi_dim_array = np.array([[1, 2, 3], [4, 5, 6]])
print("Original Array:")
print(multi_dim_array)
print("\nIterating using .flat:")
for element in multi_dim_array.flat:
print(element)
# flat can also be used for assignment
flat_view = multi_dim_array.flat
flat_view[0] = 99
print("\nArray after assignment via .flat:")
print(multi_dim_array)

The output for this code is:

Original Array:
[[1 2 3]
[4 5 6]]
Iterating using .flat:
1
2
3
4
5
6
Array after assignment via .flat:
[[99 2 3]
[ 4 5 6]]

Codebyte Example

Use the codebyte below to access elements of a multi-dimensional array using a single index via flat:

Code
Output

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours