Write Python. Understand every error.

Open the editor

Error guide · NumPy errors

ValueError: cannot reshape array of size 6 into shape (4,2)

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

Example

import numpy as np

a = np.arange(6)
print(a.reshape(4, 2))

What Python says

ValueError: cannot reshape array of size 6 into shape (4,2)

As printed by Python 3.12. Other versions may word it slightly differently.

Try this code in Py-CRAFT

Why it happens

reshape rearranges the same elements, so the number of rows times the number of columns must equal the size of the array. Six elements can make 3 by 2, 2 by 3 or 6 by 1, but not 4 by 2, which needs eight.

How to fix it

import numpy as np

a = np.arange(6)
print(a.reshape(3, 2))

Output: [[0 1] ⏎ [2 3] ⏎ [4 5]]

Tips

Learn the ideas behind it

Other common errors

Share this page: