Arrays - shape, reshape and flatten

NumPy - The Basics

1 min read

Published Sep 22 2025, updated Aug 17 2026


11
0
0
0

NumPyPython

shape

  • An attribute that tells you the dimensions (rows, columns, etc.) of an array.
  • Returns a tuple.

Example:

import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])print(arr.shape)  # → (2, 3)   (2 rows, 3 columns)




reshape()

  • Changes the shape of an array without changing its data.
  • The new shape must have the same total number of elements.
  • You can use -1 to let NumPy infer one dimension automatically.

Examples:

arr = np.arange(12)   # [0 1 2 3 4 5 6 7 8 9 10 11]# Reshape to 3x4reshaped = arr.reshape(3, 4)print(reshaped)# → [[ 0  1  2  3]#    [ 4  5  6  7]#    [ 8  9 10 11]]# Reshape to 2x2x3reshaped3d = arr.reshape(2, 2, 3)print(reshaped3d)# → [[[ 0  1  2]#     [ 3  4  5]]#    [[ 6  7  8]#     [ 9 10 11]]]# Let NumPy infer one dimensionauto = arr.reshape(-1, 6)print(auto.shape)  # → (2, 6)

  • The total number of elements must remain the same.
  • If not, NumPy raises a ValueError.

Example:

arr = np.arange(9)  # 1D array with 9 elements: [0 1 2 3 4 5 6 7 8]# Attempt to reshape to 2x5 (10 elements) → incompatiblearr.reshape(2, 5)# → ValueError: cannot reshape array of size 9 into shape (2,5)

  • Reason: You can’t magically create or remove elements.
  • Always make sure that original_size = new_shape_product.
  • For arr.reshape(m, n), m * n must equal arr.size.




flatten()

  • Converts a multi-dimensional array into a 1D array.
  • Returns a copy (so modifying the result won’t affect the original array).

Example:

arr = np.array([[1, 2], [3, 4], [5, 6]])print(arr.flatten())# → [1 2 3 4 5 6]
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
NumPy - The Basics | Arrays - shape, reshape and flatten | SimpleSteps.guide