All sample questions / Python

Python Lists, Tuples and Slicing, what does print(a) print after a = [[1, 2], [3, 4]]?

Block 4, Lists, Tuples and Slicing, question 12 of the Python sample

a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
print(a)

What does this print?

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

Answer, C. [[1, 2, 99], [3, 4]]

A. [[1, 2, 99], [3, 4], [1, 2, 99], [3, 4]]
Assumes copying the outer list duplicates its inner lists as well, doubling the total number of sublists.
B. [[1, 2], [3, 4]]
Assumes copy() makes a fully independent copy at every level, so mutating a shared inner list through b would not be visible through a.
C. [[1, 2, 99], [3, 4]]
Correct. copy() only makes a shallow copy, so b holds new outer list slots that still point at the very same inner lists as a, and mutating one of those inner lists through b is visible through a as well.
D. [[1, 2], [3, 4, 99]]
Assumes the append lands on the second inner list instead of the first, misreading which sublist index 0 refers to.

A shallow copy duplicates only the outer container, the references it holds still point at the same nested objects as the original. To get inner lists that can be mutated independently, a deep copy is needed instead of a shallow one.

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.