Arrays - shape, reshape and flatten
NumPy - The Basics
1 min read
This section is 1 min read, full guide is 14 min read
Published Sep 22 2025
11
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
NumPyPython
shape
- An attribute that tells you the dimensions (rows, columns, etc.) of an array.
- Returns a tuple.
Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)
# → (2, 3) (2 rows, 3 columns)
Copy to Clipboard
Toggle show comments
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
-1to 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 3x4
reshaped = arr.reshape(3, 4)
print(reshaped)
# → [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# Reshape to 2x2x3
reshaped3d = arr.reshape(2, 2, 3)
print(reshaped3d)
# → [[[ 0 1 2]
# [ 3 4 5]]
# [[ 6 7 8]
# [ 9 10 11]]]
# Let NumPy infer one dimension
auto = arr.reshape(-1, 6)
print(auto.shape)
# → (2, 6)
Copy to Clipboard
Toggle show comments
- 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) → incompatible
arr.reshape(2, 5)
# → ValueError: cannot reshape array of size 9 into shape (2,5)
Copy to Clipboard
Toggle show comments
- Reason: You can’t magically create or remove elements.
- Always make sure that
original_size = new_shape_product. - For
arr.reshape(m, n),m * nmust equalarr.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]
Copy to Clipboard
Toggle show comments














