All sample questions / NumPy

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

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

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

What does this print?

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

Answer, A. [111, 222, 30, 40, 50]

A. [111, 222, 30, 40, 50]
Correct. Assigning through a fancy index writes directly into the original array at the named positions, position 0 becomes 111 and position 1 becomes 222.
B. [222, 111, 30, 40, 50]
Swaps which value lands on which position, as if the assigned list were applied in reverse order.
C. [10, 20, 30, 40, 50]
Assumes an assignment through a fancy index list has no effect on the original array, the way reading through one produces a copy.
D. [111, 222, 30]
Assumes the assignment also shortens the array down to only the two positions that were written.

Fancy indexing produces a copy when reading, but assigning through the same kind of index writes straight into the original array at each named position. This is a genuine exception to the reading rule and is exactly how a batch update to specific positions is usually written.

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.