How to Get the Shape of a Numpy Array?

NumPy is a popular Python library for data science. The focus of the library is computations on arrays, vectors, and matrices. If you work with data, there is no way that you can avoid NumPy.

In this tutorial, you’ll learn more about the shape of a NumPy array. In particular, you’re going to learn the solution to the following question:

How to Get the Shape of a Numpy Array?

Answer: You can access the shape of a NumPy array via the array attribute array.shape.

To get the shape of an n-dimensional NumPy array arr, call arr.shape that returns a tuple with n values, one per dimension. Each tuple value gives the number of elements along this dimension. For example, a two-dimensional array with x rows and y columns has the shape (x,y).

NumPy Shape

Here’s an example of a two-dimensional array:

import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Output: (2, 3)

Here’s an example of a one-dimensional array:

import numpy as np

arr = np.array([1, 2, 3])

# Output: (3,)

And here’s an example of a three-dimensional array:

import numpy as np

arr = np.array([[[1, 2], [3, 4]],
                [[5, 6], [7, 8]]])

# Output: (2, 2, 2)

Now, let’s test and train your NumPy shape skills:

NumPy Shape Puzzle

Can you solve the following puzzle about NumPy’s shape attribute?

import numpy as np

# salary in ($1000) [2015, 2016, 2017]
dataScientist = [133, 132, 137]
productManager = [127, 140, 145]
designer = [118, 118, 127]
softwareEngineer = [129, 131, 137]

a = np.array([dataScientist,


Exercise: What is the output of this puzzle?

You can solve this puzzle interactively on our Finxter app here:

We work on salary data of four jobs:

  • data scientists,
  • product managers,
  • designers, and
  • software engineers.

We create four lists that store the yearly average salary of the four jobs in thousand dollars for three subsequent years.

Then, we merge these four lists into a two-dimensional array (denoted as matrix), i.e., a list of lists. Each salary list of a single job becomes a row of this matrix. Each row has three columns, one for each year.

The puzzle prints the shape of this matrix which is the number of elements in each dimension. For example, a matrix with n rows and m columns has shape (n,m). As our two-dimensional matrix has 4 rows and 3 columns, the solution of this puzzle is 4 and 3.

Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy