Consider the following Python code snippet.
a = [1, 2, 3]
b = a
c = a[:]
a += [4]
a = a + [5]
b.append(6)
What is the final value of c?
A
Step-by-Step Solution
Key idea: This is a list aliasing and mutation question. The key is tracking which operations mutate the existing list versus creating a new one, and understanding that slicing creates a shallow copy.
Step 1: Initial state
- a = [1, 2, 3]
- b = a (b points to the same list as a)
- c = a[:] (c is a separate copy: [1, 2, 3])
Step 2: a += [4]
- The += operator mutates the list in place
- Both a and b now point to [1, 2, 3, 4]
- c remains [1, 2, 3]
Step 3: a = a + [5]
- The + operator creates a new list and rebinds a
- a now points to [1, 2, 3, 4, 5]
- b still points to [1, 2, 3, 4]
- c remains [1, 2, 3]
Step 4: b.append(6)
- This mutates the list that b points to
- b becomes [1, 2, 3, 4, 6]
- a remains [1, 2, 3, 4, 5]
- c remains [1, 2, 3]
Final value of c: [1, 2, 3]
Answer: A