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.

Steps to flatten a NumPy array:

  1. 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())
  2. 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.

  3. 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.

  4. 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

  5. Remove the test script if it was only used to confirm behavior.
    $ rm array-flatten.py