Reshaping and Flattening

Reviewed & published by Brayan K

Reshaping is rearranging the same array elements into a new layout of rows, columns, and dimensions, while flattening is collapsing a multi-dimensional array back down into a single 1D line — neither changes the underlying values.

Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

In this lesson you'll reshape with explicit sizes, let NumPy infer a dimension with -1, flatten with ravel() and flatten(), transpose with .T, and add a new axis.

What You'll Learn in This Lesson

1 Reshaping with .reshape()

reshape(rows, cols) takes a flat array and folds its elements into a new grid, filling row by row. The data stays the same — only the arrangement changes. The new shape must hold exactly as many elements as the original.

import numpy as np

arr = np.arange(12)   # [ 0  1  2 ... 11 ]  (12 elements)

# Fold 12 elements into 3 rows of 4
grid = arr.reshape(3, 4)
print(grid)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(grid.shape)   # (3, 4)

# ✅ Expected output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# (3, 4)

Expected output: a 3×4 grid of 0–11, then (3, 4).

2 Letting NumPy Infer a Dimension with -1

Pass -1 for one dimension and NumPy figures out its size from the total element count. Useful when you know you want, say, 3 rows but don't want to compute the column count yourself.

import numpy as np

arr = np.arange(12)

# 3 rows, and let NumPy compute the columns (12 / 3 = 4)
print(arr.reshape(3, -1).shape)   # (3, 4)

# 2 columns, and let NumPy compute the rows (12 / 2 = 6)
print(arr.reshape(-1, 2).shape)   # (6, 2)

# A lone -1 flattens to 1D
print(arr.reshape(3, 4).reshape(-1).shape)   # (12,)

# ✅ Expected output:
# (3, 4)
# (6, 2)
# (12,)

Expected output: (3, 4), (6, 2), and (12,).

3 Flattening: ravel() vs flatten()

Both ravel() and flatten() collapse a multi-dimensional array into 1D. The difference is memory: ravel() returns a view (shares memory with the original when possible), while flatten() always returns an independent copy.

import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])

# ravel() -> a view that may share memory
r = grid.ravel()
print(r)        # [1 2 3 4 5 6]
r[0] = 99
print(grid[0, 0])   # 99  -> the original changed!

# flatten() -> an independent copy
grid2 = np.array([[1, 2], [3, 4]])
f = grid2.flatten()
f[0] = 99
print(grid2[0, 0])  # 1   -> the original is untouched

# ✅ Expected output:
# [1 2 3 4 5 6]
# 99
# 1

Expected output: [1 2 3 4 5 6], then 99 (ravel changed the source) and 1 (flatten left it alone).

4 Transposing with .T and Adding a Dimension

.T transposes an array — it flips rows and columns so the element at [i, j] moves to [j, i]. To add a brand-new axis (e.g. turn a 1D array into a single column), use np.newaxis or an equivalent reshape.

import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])

print(grid.T)
# [[1 4]
#  [2 5]
#  [3 6]]
print(grid.shape, grid.T.shape)   # (2, 3) (3, 2)

# Turn a 1D array into a column with a new axis
row = np.array([1, 2, 3])
col = row[:, np.newaxis]
print(col)
# [[1]
#  [2]
#  [3]]
print(col.shape)   # (3, 1)

# ✅ Expected output:
# [[1 4]
#  [2 5]
#  [3 6]]
# (2, 3) (3, 2)
# [[1]
#  [2]
#  [3]]
# (3, 1)

Expected output: the 3×2 transpose, (2, 3) (3, 2), then the column array and (3, 1).

🎯 YOUR TURN: Fill in the Blanks

Replace each ___ so the program reshapes, infers a dimension, and transposes.

import numpy as np

arr = np.arange(8)

print(arr.reshape(2, ___).shape)  # want 2 rows of 4 -> (2, 4)

print(arr.reshape(___, 2).shape)  # want NumPy to infer the rows -> (4, 2)

grid = np.array([[1, 2],
                 [3, 4]])
print(grid.___)                   # want the transpose attribute -> [[1 3] [2 4]]

Expected output: (2, 4), (4, 2), and the transposed grid. (Answers: 4, -1, T.)

⚠️ Common Errors & Quick Reference

❌ ValueError: cannot reshape array of size 12 into shape (5,5)

The new shape needs a different number of elements than the array holds.

✅ Fix: make rows × cols equal the size. 12 fits (3, 4) or (2, 6), not (5, 5).

❌ Editing a flattened array changed the original

You used ravel(), which can return a view that shares memory.

✅ Fix: use flatten() when you want an independent copy.

TaskCode
Reshape to a gridarr.reshape(3, 4)
Infer a dimensionarr.reshape(3, -1)
Flatten (view)arr.ravel()
Flatten (copy)arr.flatten()
Transposearr.T
Add an axisarr[:, np.newaxis]

🏆 Mini Challenge: Build a Multiplication Table

Reshape a range into a 3×4 grid, flatten it back, and transpose the grid — all without changing the values.

import numpy as np

data = np.arange(1, 13)   # [ 1  2  3 ... 12 ]

# 1. Fold into 3 rows, infer the columns
grid = data.reshape(3, -1)
print(grid.shape)   # (3, 4)

# 2. Flatten it back to 1D with a copy
print(grid.flatten())   # [ 1  2  3  4  5  6  7  8  9 10 11 12]

# 3. Transpose the grid
print(grid.T.shape)   # (4, 3)

# ✅ Expected output:
# (3, 4)
# [ 1  2  3  4  5  6  7  8  9 10 11 12]
# (4, 3)

❓ Frequently Asked Questions

Lesson complete — you can reshape anything!

You now reshape with explicit sizes, let NumPy infer a dimension with -1, flatten with ravel() and flatten() (knowing the view-vs-copy difference), transpose with .T, and add new axes.

Practice quiz

What does arr.reshape(2, 3) do to a 6-element array?

  • Arranges it into 2 rows of 3 columns
  • Sorts it
  • Removes 3 elements
  • Doubles its values

Answer: Arranges it into 2 rows of 3 columns. reshape rearranges the same elements into a 2-row, 3-column grid without changing the data.

What does passing -1 for one dimension in reshape mean?

  • Reverse the array
  • Let NumPy compute that size from the total count
  • Remove a dimension
  • Use negative indexing

Answer: Let NumPy compute that size from the total count. -1 tells NumPy to infer that dimension's size from the total number of elements.

What does arr.reshape(3, -1) give for a 12-element array?

  • Shape (12, 1)
  • An error
  • Shape (3, 4)
  • Shape (4, 3)

Answer: Shape (3, 4). With 12 elements and 3 rows, NumPy computes 4 columns, giving (3, 4).

What is the key difference between ravel() and flatten()?

  • ravel sorts, flatten does not
  • They are identical
  • ravel works only on 1D
  • ravel may return a view; flatten always returns a copy

Answer: ravel may return a view; flatten always returns a copy. ravel returns a view sharing memory when possible; flatten always returns an independent copy.

If you edit a ravel() result, what can happen to the original?

  • It may change because they can share memory
  • It is always safe
  • It gets deleted
  • It gets sorted

Answer: It may change because they can share memory. ravel may share memory, so editing the result can change the original array.

How many -1 dimensions can a single reshape call have?

  • As many as you want
  • Only one
  • Two
  • Zero

Answer: Only one. NumPy can solve for only one unknown dimension, so only one -1 is allowed.

What does .T do to a 2D array?

  • Truncates it
  • Totals the elements
  • Transposes rows and columns
  • Tiles it

Answer: Transposes rows and columns. .T transposes, moving the element at [i, j] to [j, i].

Why does reshaping a size-12 array into (5, 5) fail?

  • 5 is prime
  • (5, 5) needs 25 elements, not 12
  • reshape needs square inputs
  • It needs a -1

Answer: (5, 5) needs 25 elements, not 12. Reshape must preserve the element count; (5, 5) requires 25 elements.

Which flattening method always gives an independent copy?

  • ravel()
  • reshape(-1)
  • flatten()
  • .T

Answer: flatten(). flatten() always returns an independent copy you can edit safely.

What shape does arr.reshape(-1, 2) give for a 12-element array?

  • (6, 2)
  • (2, 6)
  • (12, 2)
  • (2, 12)

Answer: (6, 2). With 2 columns and 12 elements, NumPy computes 6 rows, giving (6, 2).

Continue this course

Frequently asked questions

What does reshape do in NumPy?

reshape changes how an array's existing elements are arranged into rows, columns, and higher dimensions, without changing the data itself. arr.reshape(2, 3) turns 6 elements into a 2-row, 3-column grid.

What does -1 mean inside reshape?

Passing -1 for one dimension tells NumPy to calculate that size automatically from the total number of elements. arr.reshape(3, -1) keeps 3 rows and works out the columns for you, so you don't have to do the division.

What is the difference between ravel and flatten?

Both turn a multi-dimensional array into 1D. ravel() returns a view that shares memory when possible (fast, no copy), while flatten() always returns an independent copy. Use flatten when you want to edit the result without affecting the original.

Why do I get a 'cannot reshape array' error?

Reshaping must preserve the total number of elements. A 12-element array can become (3, 4) or (2, 6) but not (5, 5), because 5 by 5 needs 25 elements. Check that rows times columns equals the original size.