Last updated

Array Shape

Definition: The shape of an array is its size along each dimension, given as a tuple. A 2D array of 3 rows and 4 columns has shape (3, 4).

Example

import numpy as np
a = np.array([[1, 2, 3],
              [4, 5, 6]])
print("shape:", a.shape)   # (2, 3)
print("ndim: ", a.ndim)    # 2 (number of dimensions)
print("size: ", a.size)    # 6 (total elements)

What each attribute tells you

  • shape — (rows, columns) for 2D
  • ndim — how many dimensions (1D, 2D, 3D...)
  • size — total number of elements

1D vs 2D

import numpy as np
a = np.array([1, 2, 3, 4])
print(a.shape)   # (4,)  -> 1D with 4 elements

A trailing comma like (4,) just means it is a one-dimensional array.

💡 Tip: checking .shape is the first thing to do when an operation gives an unexpected error — mismatched shapes are the usual cause.

Try it Yourself
Output

          
Ad · responsive