This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: NumPy arrays

NumPy array attributes

face Josiah Wang

As you should be aware by now, np.array (or rather np.ndarray) is a class. Therefore, a np.array can have attributes associated with it.

The official documentation provides a complete list of np.array attributes.

Rather than me explaining the attributes, let’s try to get you to remember the most important attributes through a quiz! Just make an informed guess from the name of the attributes (no penalty for getting it wrong!)

1 2 3 4 5

Question 1

What is the output of the following piece of code? Make a guess!

import numpy as np

x = np.array([[[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0 ,1 ,2, 3],
               [4, 5, 6, 7]]])
print(x.ndim)

3
Explanation:

The .ndim attribute gives the number of dimensions (or axes) of the np.array instance. In this case, it is a 3D array.

Question 2

What is the output of the following piece of code? Make a guess! Hint: Think of a list inside a list inside a list!

import numpy as np

x = np.array([[[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0 ,1 ,2, 3],
               [4, 5, 6, 7]]])
print(x.shape)

(3, 2, 4)
Explanation:

This might be a confusing one to guess! The .shape attribute gives you a tuple indicating the number of elements in each axis. So (3, 2, 4) represents a 3 \times 2 \times 4 array. The outermost array has 3 elements, the array inside that has 2 elements, and the innermost array has 4 elements.

Question 3

What is the output of the following piece of code? Make a guess!

import numpy as np

x = np.array([[[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0, 1, 2, 3],
               [4, 5, 6, 7]],
              [[0 ,1 ,2, 3],
               [4, 5, 6, 7]]])
print(x.size)

24
Explanation:

The .size attribute gives you the total number of elements in the array. In this example, it is 3\times2\times4=24.

Question 4

Back to the shape attribute! What is the output of the following piece of code?

import numpy as np

x = np.array([[0, 1, 2, 3]])
print(x.shape)

(1, 4)
Explanation:

The outermost array has only 1 element, and the innermost array has 4 elements. So this is a 1\times4 array, or shape (1,4).

Question 5

A last question with the shape attribute again! What is the output of the following piece of code? This might be a trick question, so be careful!

import numpy as np

x = np.array([0, 1, 2, 3])
print(x.shape)

(4,)
Explanation:

This is a 1D NumPy array with 4 elements (or a 4D vector in Mathematical terms). So there is only 1 axis, which has 4 elements. The .shape attribute gives you a tuple, and so this is a singleton tuple with only one element.