arrays
dimensionality reduction
ND arrays
1D arrays
data transformation

From ND to 1D arrays

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Converting multidimensional (ND) arrays to one-dimensional (1D) arrays — called flattening or raveling — is one of the most common array operations in scientific computing. Machine learning models typically expect 1D feature vectors, many C libraries require contiguous 1D buffers, and serialization formats work with flat sequences. NumPy provides several methods to flatten arrays, each with different memory and performance characteristics.

Method 1: ndarray.flatten()

flatten() always returns a copy of the data as a contiguous 1D array:

python
1import numpy as np
2
3arr = np.array([[1, 2, 3],
4                [4, 5, 6]])
5
6flat = arr.flatten()
7print(flat)        # [1 2 3 4 5 6]
8print(flat.shape)  # (6,)
9
10# Modifying the flattened array does NOT affect the original
11flat[0] = 99
12print(arr[0, 0])   # 1 — unchanged

Row-major vs Column-major Order

python
1arr = np.array([[1, 2, 3],
2                [4, 5, 6]])
3
4# 'C' order (row-major, default) — reads across rows
5print(arr.flatten('C'))  # [1 2 3 4 5 6]
6
7# 'F' order (column-major, Fortran order) — reads down columns
8print(arr.flatten('F'))  # [1 4 2 5 3 6]
9
10# 'A' order — 'F' if array is Fortran-contiguous, else 'C'
11# 'K' order — flattens in memory layout order

Method 2: ndarray.ravel()

ravel() returns a 1D view when possible, avoiding a copy:

python
1arr = np.array([[1, 2, 3],
2                [4, 5, 6]])
3
4raveled = arr.ravel()
5print(raveled)  # [1 2 3 4 5 6]
6
7# Modifying the raveled array DOES affect the original (it's a view)
8raveled[0] = 99
9print(arr[0, 0])  # 99 — changed!

ravel() is faster and more memory-efficient than flatten() because it avoids copying data when the array is already contiguous. Use flatten() when you need an independent copy.

python
1arr = np.array([[1, 2, 3],
2                [4, 5, 6]])
3
4# ravel returns a view (no copy) for C-contiguous arrays
5r = arr.ravel()
6print(np.shares_memory(arr, r))  # True
7
8# flatten always copies
9f = arr.flatten()
10print(np.shares_memory(arr, f))  # False

Method 3: ndarray.reshape(-1)

reshape(-1) reshapes to 1D, returning a view when possible (same behavior as ravel()):

python
1arr = np.array([[1, 2, 3],
2                [4, 5, 6]])
3
4flat = arr.reshape(-1)
5print(flat)  # [1 2 3 4 5 6]
6
7# The -1 tells NumPy to infer the size
8# Equivalent to arr.reshape(arr.size)

reshape(-1) is commonly used in machine learning pipelines where you chain multiple reshape operations:

python
1# Flatten a batch of images: (32, 28, 28) → (32, 784)
2images = np.random.rand(32, 28, 28)
3flat_images = images.reshape(32, -1)
4print(flat_images.shape)  # (32, 784)

Method 4: np.concatenate or np.hstack

For flattening a list of arrays into one 1D array:

python
1arrays = [np.array([1, 2]), np.array([3, 4, 5]), np.array([6])]
2
3flat = np.concatenate(arrays)
4print(flat)  # [1 2 3 4 5 6]
5
6# For 2D arrays, flatten each first
7matrices = [np.array([[1, 2], [3, 4]]), np.array([[5, 6]])]
8flat = np.concatenate([m.ravel() for m in matrices])
9print(flat)  # [1 2 3 4 5 6]

Higher-Dimensional Arrays

All methods work on arrays of any dimensionality:

python
1# 3D array (e.g., RGB image)
2arr_3d = np.arange(24).reshape(2, 3, 4)
3print(arr_3d.shape)           # (2, 3, 4)
4print(arr_3d.flatten().shape) # (24,)
5print(arr_3d.ravel().shape)   # (24,)
6
7# 4D array (e.g., batch of images)
8arr_4d = np.zeros((10, 3, 32, 32))
9print(arr_4d.flatten().shape)  # (30720,)

Comparison of Methods

MethodReturns CopySpeedWhen to Use
flatten()AlwaysSlowerNeed independent copy
ravel()Only if neededFastestRead-only or safe mutation
reshape(-1)Only if neededFastChaining reshape operations
np.concatenateAlwaysModerateMerging multiple arrays

Flattening in Other Languages

Python Lists (No NumPy)

python
1# Nested list flattening
2nested = [[1, 2, 3], [4, 5], [6]]
3
4# List comprehension
5flat = [x for sublist in nested for x in sublist]
6print(flat)  # [1, 2, 3, 4, 5, 6]
7
8# itertools.chain
9from itertools import chain
10flat = list(chain.from_iterable(nested))

PyTorch

python
1import torch
2
3tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
4flat = tensor.flatten()        # Returns a view when possible
5flat = tensor.reshape(-1)      # Equivalent
6flat = tensor.view(-1)         # Requires contiguous memory

Common Pitfalls

  • Unintended mutation with ravel(): Since ravel() returns a view, modifying the result modifies the original array. Use flatten() if you need an independent copy.
  • Non-contiguous arrays: Transposed or sliced arrays may not be contiguous in memory. ravel() and reshape(-1) will silently make a copy in these cases. Check with arr.flags['C_CONTIGUOUS'].
  • Order matters for ML: Most frameworks expect row-major ('C') order. If you flatten a Fortran-order array with the default 'C' order, the element sequence may be unexpected. Explicitly pass order='C' or order='F'.
  • Memory with large arrays: flatten() on a 10 GB array allocates another 10 GB. Use ravel() to avoid the copy, or process the array in chunks.
  • Nested Python lists vs NumPy: np.array(nested_list).flatten() only works if the nested list is rectangular (all sublists have the same length). For ragged lists, use itertools.chain.from_iterable.

Summary

  • Use arr.ravel() for the fastest, memory-efficient flattening (returns a view when possible)
  • Use arr.flatten() when you need a guaranteed independent copy
  • Use arr.reshape(-1) when chaining with other reshape operations
  • The default order is row-major ('C') — elements are read across rows first
  • For non-NumPy nested lists, use list comprehensions or itertools.chain.from_iterable

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.