Many array workflows move between grids, matrices, and one-dimensional vectors. In NumPy, flattening keeps the same values but collapses the shape so downstream code can receive a single sequence.
ndarray.flatten() returns a new one-dimensional array instead of a view over the original buffer. That copy boundary matters when the flattened result may be edited, saved, or handed to code that mutates its input.
Traversal order is separate from the output shape. The default order=“C” reads rows first, while order=“F” reads columns first; ravel() is the memory-sharing alternative only when a view is acceptable.
Related: Reshape an array
Related: Check view or copy state
Related: Transpose an array
Steps to flatten a NumPy array:
- Create a script that flattens a matrix in row-major and column-major order, then compares copy behavior.
- array-flatten.py
import numpy as np grid = np.array([[10, 20, 30], [40, 50, 60]]) flat = grid.flatten() column_order = grid.flatten(order="F") raveled = grid.ravel() print("shape:", grid.shape) print("flat:", flat.tolist()) print("flat shape:", flat.shape) print("order F:", column_order.tolist()) print("flatten shares memory:", np.shares_memory(grid, flat)) print("ravel shares memory:", np.shares_memory(grid, raveled)) flat[0] = -1 print("after flatten edit:", grid.tolist()) raveled[1] = 999 print("after ravel edit:", grid.tolist())
- Run the script and confirm the one-dimensional output.
$ python array-flatten.py shape: (2, 3) flat: [10, 20, 30, 40, 50, 60] flat shape: (6,) order F: [10, 40, 20, 50, 30, 60] flatten shares memory: False ravel shares memory: True after flatten edit: [[10, 20, 30], [40, 50, 60]] after ravel edit: [[10, 999, 30], [40, 50, 60]]
The shape changes from (2, 3) to (6,), and flatten shares memory stays False because flatten() returns a copy.
- Keep the default row-major order when the consumer expects rows to stay together.
The flat line reads the first row before the second row. Passing order=“F” reads down each column first and produces [10, 40, 20, 50, 30, 60] from the same source array.
- Use flatten() instead of ravel() when edits to the flattened result must stay isolated.
The after flatten edit line leaves grid unchanged. The after ravel edit line changes the source array because ravel() can return a view for this contiguous layout.
Related: Check view or copy state - Remove the test script if it was only used to confirm behavior.
$ rm array-flatten.py
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.