LESSON 162 · PRACTICAL PYTHON28 min

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.

Before you start: Lists · Functions

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

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 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.

  2. 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

  3. 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

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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

PYTHON
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(a.shape, b.shape, b.size)
print(b.tolist())
EXPECTED OUTPUT
(6,) (2, 3) 6
[[0, 1, 2], [3, 4, 5]]

Reshape changes axes without changing the six values.

02. Infer one dimension

PYTHON
import numpy as np
a = np.arange(12)
print(a.reshape(-1, 3).shape)
print(a.reshape(3, -1).shape)
EXPECTED OUTPUT
(4, 3)
(3, 4)

The location of -1 decides which dimension NumPy infers.

03. Check whether a simple reshape shares data

PYTHON
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])
EXPECTED OUTPUT
True
99

This 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.

01 / 03

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.

PYTHON
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(a.shape, b.shape, b.size)
print(b.tolist())
EXPECTED OUTPUT
(6,) (2, 3) 6
[[0, 1, 2], [3, 4, 5]]
Follow the reasoning
  1. Run the six-element example.
  2. Multiply the result dimensions and compare with size.
02 / 03

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.

PYTHON
import numpy as np
a = np.arange(12)
print(a.reshape(-1, 3).shape)
print(a.reshape(3, -1).shape)
EXPECTED OUTPUT
(4, 3)
(3, 4)
Follow the reasoning
  1. Predict both shapes before running.
  2. Explain which dimension stays fixed in each call.
03 / 03

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.

PYTHON
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])
EXPECTED OUTPUT
True
99
Follow the reasoning
  1. Run the view example and observe the source value.
  2. 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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnImplement reshape_rows(values, columns). Return a two-dimensional NumPy array whose rows have exactly columns entries. Reject a nonpositive or noninteger column count, a non-1D input, and any element count that cannot fill complete rows. The sample must print [[1, 2, 3], [4, 5, 6]].
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.

    01.Can six elements be reshaped into shape (4, 2)?

    02.What does reshape(-1, 3) infer for an array of 12 elements?

    03.Does reshape always produce an independent copy?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Reversing rows and columns

    COMMON MISTAKE
    array.reshape(columns, -1)
    FIX
    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

    COMMON MISTAKE
    np.arange(6).reshape(4, 2)
    FIX
    np.arange(6).reshape(2, 3)

    What happens: ValueError because the requested shape requires eight elements.
    Reshape preserves the total element count.

    Browse this lesson’s problem fixes

    Sources and further reading