NumPy reshape: change array dimensions without shape errors
Reshape a one-dimensional NumPy array into a chosen number of columns, with a clear check for incompatible sizes.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: NumPy reshape: change array dimensions without shape errors
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
NumPy reshape changes how existing elements are arranged into axes; it does not add, remove, or reorder values. An array with six elements can become a 2 by 3 table or a 3 by 2 table, but not a 4 by 2 table. The product of the requested dimensions must equal the array's size. This is the first thing to check when a reshape call raises ValueError. Today we will test the claim with a tiny example, inspect a misleading first attempt, and finish with a verification case. Reshape a one-dimensional NumPy array into a chosen number of columns, with a clear check for incompatible sizes.
- 00:40
For a flat input and a fixed number of columns, reshape(-1, columns) tells NumPy to infer the number of rows. Only one dimension can be -1. If the element count is not divisible by the requested column count, inference cannot produce a rectangular result. Validate a positive integer column count before dividing; bool should not count as a column count even though bool is an int subclass. The first run is intentionally incomplete or incorrect. The number supplied becomes the row count instead of the requested column count. Read the actual output before editing the code; a familiar-looking command can still
- 01:20
answer the wrong question. The phrase NumPy reshape often appears beside a ValueError that says an array cannot be reshaped into the requested shape. The useful diagnosis is arithmetic: multiply the requested axis lengths and compare that product with array.size. Six values fit two rows of three, or three rows of two. They do not fit four rows of two because that would need eight values. Start with a flat array so the source shape is clear. Print the original and requested shapes as well as size rather than relying on a visually formatted array. NumPy uses row-major order by default for this simple case, so the first three
- 02:02
values become the first row. No value is invented to fill an undersized array. We use a second run to make the cause visible. The printed values are small enough to check by hand. If they disagree with your prediction, pause and identify the assumption that changed. A common data-preparation question asks for a specific number of columns while letting the number of rows depend on input length. The -1 placeholder expresses exactly that. With twelve elements and three columns, NumPy infers four rows. Put the -1 in the other position and the interpretation changes: three rows and four columns.
- 02:45
Only one dimension may be inferred in a reshape call. An inferred dimension is still subject to the size rule. Five values cannot form complete rows of three, so reshape(-1, 3) raises ValueError. The task checks divisibility before calling reshape to offer a deliberate input contract. It also rejects zero columns before modulo or division and requires a one-dimensional input instead of silently flattening a matrix. Now compare the corrected run with the earlier one. The important change is the rule encoded in the operation, not merely the final display. Run the code and inspect the returned values as well as their interpretation.
- 03:29
Reshape may return a view that shares memory with the source when its memory layout allows it, or a copy when it does not. Do not promise that reshape always copies or always shares data. The lesson's simple contiguous array demonstrates a view; code that needs independence should explicitly call copy() on the reshaped result. Compare shape and size before interpreting the numbers in a matrix. Reshape rearranges access to stored values, and a contiguous array can often be viewed with new axes without copying its data. In the demonstrated case, shares_memory reports True, and changing the first element through the reshaped array changes the source.
- 04:11
That behavior can be efficient, but it can surprise code that assumes an independent table was created. NumPy may have to copy for a different input layout or requested order. Do not rely on either outcome as a universal guarantee. If the caller needs independence, use reshaped.copy() and verify np.shares_memory is False. The practice task only promises a correct shape and values. Its tests avoid asserting memory sharing because the lesson's public contract is about dimensions, not storage ownership. The final run checks a different condition so a special-case answer cannot pass unnoticed.
- 04:52
Try the linked browser task and use the guide when you need a smaller step. The source links on the lesson page give the complete API behavior. The browser exercise creates arrays from small Python lists. In a local environment install NumPy with python -m pip install numpy. The task returns a two-dimensional array with the requested column count and raises ValueError for non-divisible lengths. A one-dimensional input is required so a preexisting matrix cannot accidentally be flattened without the caller noticing. One more diagnostic is to write down the desired shape before touching the program.
- 05:33
For six elements, two times three is six, while four times two is eight. A ValueError is therefore useful information, not a NumPy malfunction. Also distinguish a row of three values, shape (1, 3), from a flat vector of three values, shape (3,). Both hold three elements, but a model or plotting API may accept only one. Print ndim when integrating with another library, and avoid flattening away an axis merely to silence an error.
Understand the concept
NumPy reshape changes how existing elements are arranged into axes; it does not add, remove, or reorder values. An array with six elements can become a 2 by 3 table or a 3 by 2 table, but not a 4 by 2 table. The product of the requested dimensions must equal the array's size. This is the first thing to check when a reshape call raises ValueError.
For a flat input and a fixed number of columns, reshape(-1, columns) tells NumPy to infer the number of rows. Only one dimension can be -1. If the element count is not divisible by the requested column count, inference cannot produce a rectangular result. Validate a positive integer column count before dividing; bool should not count as a column count even though bool is an int subclass.
Reshape may return a view that shares memory with the source when its memory layout allows it, or a copy when it does not. Do not promise that reshape always copies or always shares data. The lesson's simple contiguous array demonstrates a view; code that needs independence should explicitly call copy() on the reshaped result. Compare shape and size before interpreting the numbers in a matrix.
The browser exercise creates arrays from small Python lists. In a local environment install NumPy with python -m pip install numpy. The task returns a two-dimensional array with the requested column count and raises ValueError for non-divisible lengths. A one-dimensional input is required so a preexisting matrix cannot accidentally be flattened without the caller noticing.
- shape is the length of each axis
- size stays constant during reshape
- -1 infers exactly one dimension
- reshape may share memory with its source
See it step by step
Read the code, predict the output, then compare it with the result.
01. Inspect shape and unchanged element count
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(a.shape, b.shape, b.size)
print(b.tolist())(6,) (2, 3) 6
[[0, 1, 2], [3, 4, 5]]Reshape changes axes without changing the six values.
02. Infer one dimension
import numpy as np
a = np.arange(12)
print(a.reshape(-1, 3).shape)
print(a.reshape(3, -1).shape)(4, 3)
(3, 4)The location of -1 decides which dimension NumPy infers.
03. Check whether a simple reshape shares data
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(np.shares_memory(a, b))
b[0, 0] = 99
print(a[0])True
99This contiguous example returns a view; different layouts can require a copy.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Count elements before choosing dimensions
The phrase NumPy reshape often appears beside a ValueError that says an array cannot be reshaped into the requested shape. The useful diagnosis is arithmetic: multiply the requested axis lengths and compare that product with array.size. Six values fit two rows of three, or three rows of two. They do not fit four rows of two because that would need eight values.
Start with a flat array so the source shape is clear. Print the original and requested shapes as well as size rather than relying on a visually formatted array. NumPy uses row-major order by default for this simple case, so the first three values become the first row. No value is invented to fill an undersized array.
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(a.shape, b.shape, b.size)
print(b.tolist())(6,) (2, 3) 6
[[0, 1, 2], [3, 4, 5]]- Run the six-element example.
- Multiply the result dimensions and compare with size.
Infer rows from a fixed column count
A common data-preparation question asks for a specific number of columns while letting the number of rows depend on input length. The -1 placeholder expresses exactly that. With twelve elements and three columns, NumPy infers four rows. Put the -1 in the other position and the interpretation changes: three rows and four columns. Only one dimension may be inferred in a reshape call.
An inferred dimension is still subject to the size rule. Five values cannot form complete rows of three, so reshape(-1, 3) raises ValueError. The task checks divisibility before calling reshape to offer a deliberate input contract. It also rejects zero columns before modulo or division and requires a one-dimensional input instead of silently flattening a matrix.
import numpy as np
a = np.arange(12)
print(a.reshape(-1, 3).shape)
print(a.reshape(3, -1).shape)(4, 3)
(3, 4)- Predict both shapes before running.
- Explain which dimension stays fixed in each call.
Treat memory sharing as an explicit choice
Reshape rearranges access to stored values, and a contiguous array can often be viewed with new axes without copying its data. In the demonstrated case, shares_memory reports True, and changing the first element through the reshaped array changes the source. That behavior can be efficient, but it can surprise code that assumes an independent table was created.
NumPy may have to copy for a different input layout or requested order. Do not rely on either outcome as a universal guarantee. If the caller needs independence, use reshaped.copy() and verify np.shares_memory is False. The practice task only promises a correct shape and values. Its tests avoid asserting memory sharing because the lesson's public contract is about dimensions, not storage ownership.
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(np.shares_memory(a, b))
b[0, 0] = 99
print(a[0])True
99- Run the view example and observe the source value.
- Name the extra method needed when mutation must be isolated.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Use np.asarray, require array.ndim == 1, check array.size % columns == 0, and call array.reshape(-1, columns).
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Reversing rows and columns
array.reshape(columns, -1)array.reshape(-1, columns)What happens: The number supplied becomes the row count instead of the requested column count.
The last dimension is the number of entries per row.
Expecting reshape to resize data
np.arange(6).reshape(4, 2)np.arange(6).reshape(2, 3)What happens: ValueError because the requested shape requires eight elements.
Reshape preserves the total element count.