Python:NumPy flat
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.
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 arraymulti_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 assignmentflat_view = multi_dim_array.flatflat_view[0] = 99print("\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:123456Array 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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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