All sample questions / NumPy

NumPy Indexing, Slicing and Masks, what does print(a.tolist()) print after a = np.array([10, 20, 30, 40, 50])?

Block 2, Indexing, Slicing and Masks, question 5 of the NumPy sample

import numpy as np
a = np.array([10, 20, 30, 40, 50])
fancy = a[[0, 1, 2]]
fancy[0] = 999
print(a.tolist())

What does this print?

  1. A. [999, 20, 30]
  2. B. [10, 20, 30]
  3. C. [10, 20, 30, 40, 50]
  4. D. [999, 20, 30, 40, 50]
Show the answer and why each option is right or wrong

Answer, C. [10, 20, 30, 40, 50]

A. [999, 20, 30]
Assumes the edit does reach the original array but only up to the length of the fancy selection.
B. [10, 20, 30]
Assumes the entire original array was replaced by the shorter fancy selection.
C. [10, 20, 30, 40, 50]
Correct. Fancy indexing always returns a new array, so changing fancy afterward has no effect on the original array a, which stays 10, 20, 30, 40, 50.
D. [999, 20, 30, 40, 50]
Assumes fancy indexing returns a view into the same memory, so the edit reaches back into the original array.

Fancy indexing with a list of positions always copies the selected elements into a brand new array, it never shares memory with the source. This is the key difference from a slice, which returns a view, editing a fancy indexed result never changes the array it was built from.

The answer above is what NumPy 2.4.4 printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 279 NumPy interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 279 NumPy questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free NumPy sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.