NumPy Shape & Reshape

Change the dimensions of an array.

✍️ 3 exercises + code challenge in this lesson
  • arr.shape gives the size of each dimension, e.g. (2, 3).
  • arr.reshape(rows, cols) returns the same data in a new shape (the total size must match).
  • Use -1 to let NumPy work out one dimension.
  • arr.flatten() turns any array into 1-D.

Key Takeaways: NumPy Shape & Reshape

Mastering NumPy Shape & Reshape helps you write clean and reliable NumPy code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

NumPy Shape & Reshape Code Example

NumPy
import numpy as np

arr = np.arange(1, 13)
print(arr.shape)
m = arr.reshape(3, 4)
print(m)
print(m.shape)
print(arr.reshape(2, -1).shape)
Output
(12,)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
(3, 4)
(2, 6)
Free sign-in required · Google login available

NumPy Shape & Reshape Practice Exercises

Check what you learned in “NumPy Shape & Reshape”.

/ 3 solved
Fill in the blank

Reshape 12 numbers into 3 rows and 4 columns.

m = arr.(3, 4)
✓ Correct! Not quite. Try again.
Multiple choice

What does -1 mean in reshape(2, -1)?

✓ Correct! Not quite. Try again.
Code challenge

Reshape np.arange(6) into 2 rows and 3 columns and print the shape.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services