TExcelTAD
Home › NumPy › NumPy Array Shape

NumPy Array Shape

The shape of an array is a tuple listing how many elements it has along each dimension. A table with 3 rows and 4 columns has shape (3, 4). Shape is the first thing to check when NumPy code doesn't behave as expected.

python · try it yourself
import numpy as np

table = np.array([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12]])
print(table.shape)          # (rows, columns)
print(table.ndim)           # number of dimensions = len(shape)
print(table.size)           # total elements = product of shape
(3, 4)
2
12

The three attributes are related: ndim == len(shape) and size is all shape numbers multiplied together (3 × 4 = 12).

Reading a shape

Read the shape tuple from the outside in: the first number counts the outermost brackets' items, the last number counts the innermost.

python · try it yourself
import numpy as np

examples = {
    "single value": np.array(42),
    "list of 5": np.array([1, 2, 3, 4, 5]),
    "one row": np.array([[1, 2, 3]]),
    "one column": np.array([[1], [2], [3]]),
    "2 images 4x4 RGB": np.zeros((2, 4, 4, 3)),
}
for name, arr in examples.items():
    print(f"{name:18} shape={arr.shape}")
single value       shape=()
list of 5          shape=(5,)
one row            shape=(1, 3)
one column         shape=(3, 1)
2 images 4x4 RGB   shape=(2, 4, 4, 3)

A few things to notice:

  • A scalar array has the empty shape ().
  • (5,) is a 1-D shape; the trailing comma is just Python's way of writing a one-element tuple.
  • (1, 3) (a row) and (3, 1) (a column) hold the same count of numbers but behave differently in arithmetic, as you will see in the Broadcasting lesson.
  • Image batches are usually (count, height, width, channels).

Shape along each axis

Since shape is a tuple, you can index it to get the size of one axis. That is useful for loops and for validating input:

python · try it yourself
import numpy as np

# Rows = students, columns = assignments
grades = np.array([[78, 92, 85],
                   [64, 70, 88],
                   [95, 91, 99],
                   [55, 80, 72]])

students, assignments = grades.shape
print(f"{students} students, {assignments} assignments")
print("len(grades) =", len(grades))     # len() gives the first axis only
print("last axis size:", grades.shape[-1])
4 students, 3 assignments
len(grades) = 4
last axis size: 3

Creating arrays with a given shape

Shapes are what you pass to constructors such as np.zeros. A common mistake is passing the numbers separately instead of as a tuple:

python · try it yourself
import numpy as np

board = np.zeros((3, 5), dtype=int)     # correct: one tuple
print(board.shape)

try:
    np.zeros(3, 5)                      # 5 is taken as the dtype argument!
except TypeError as err:
    print("TypeError:", err)
(3, 5)
TypeError: Cannot interpret '5' as a data type

Shapes change with operations

Many operations change the shape. Reducing along an axis removes that axis, and indexing with an integer drops a dimension:

Expression (a.shape == (3, 4)) Result shape
a[0] (4,)
a[:, 0] (3,)
a[:2] (2, 4)
a.sum() () (a scalar)
a.sum(axis=0) (4,)
a.sum(axis=1) (3,)
a.T (4, 3)
python · try it yourself
import numpy as np

a = np.arange(12).reshape(3, 4)
print(a[0].shape, a[:, 0].shape, a.sum(axis=0).shape, a.T.shape)
(4,) (3,) (4,) (4, 3)

Test yourself

What is the shape of np.array([[1, 2], [3, 4], [5, 6]])?

  1. (2, 3)
  2. (3, 2)
  3. (6,)
  4. (3,)

An array has shape (2, 3, 4). What is its size?

  1. 9
  2. 24
  3. 3
  4. 234

What does len(a) return for an array of shape (5, 2)?

  1. 2
  2. 5
  3. 10
  4. 7