All sample questions / Python

Python Mutability, References and Copying, what does print(b) print after a = [1, 2]?

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

a = [1, 2]
b = a
a = a + [3]
print(b)

What does this print?

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

Answer, C. [1, 2]

A. [3]
Assumes b ends up bound to the freshly built list instead of keeping its original reference.
B. []
Assumes the plain assignment on a clears the object that b points to.
C. [1, 2]
Correct. The plus operator builds a brand new list and only a is rebound to it, b still refers to the original, unchanged list.
D. [1, 2, 3]
Confuses this with the augmented case and assumes the addition mutates the original list that b also references.

Unlike +=, the plain + operator on two lists never mutates either operand, it always returns a new list holding the concatenated elements. Rebinding a to that new list has no effect on any other name that still points to the list a used to reference, which is exactly the situation for b.

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

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