All sample questions / Python

What does print(original['items']) print? Python Mutability, References and Copying

Block 7, Mutability, References and Copying, question 17 of the Python sample

import copy

original = {'items': [1, 2]}
clone = copy.copy(original)
clone['items'] = [9, 9]
print(original['items'])

What does this print?

  1. A. []
  2. B. [1, 2, 9, 9]
  3. C. [1, 2]
  4. D. [9, 9]
Show the answer and why each option is right or wrong

Answer, C. [1, 2]

A. []
Assumes reassigning a key on the copy clears the matching entry in original.
B. [1, 2, 9, 9]
Assumes the new list is appended to the existing one instead of replacing it inside clone's own mapping.
C. [1, 2]
Correct. Reassigning the key on the shallow copy only changes what clone maps that key to, it never mutates the list object that original still holds under the same key.
D. [9, 9]
Confuses reassigning a key on the copy with mutating the shared list value in place.

A shallow copy of a dictionary is still its own independent mapping, even though the values it holds are shared with the source. Rebinding a key on the copy, as opposed to mutating the value stored under it, only changes the copy's own mapping and leaves the original dictionary's entry exactly as it was.

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

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

Get the 600 Python questions, 9 euros

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

Or play the free Python 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.