PCEP-30-02 · Question #347
What is the expected output of the following code? ``python collection = [] collection.append(1) collection.insert(0, 2) duplicate = collection duplicate.append(3) print(len(collection) +…
The correct answer is D. 6. Option D is correct because duplicate = collection does not create a copy - it creates a second reference to the same list object in memory. So when duplicate.append(3) runs, it modifies the one shared list, leaving both collection and duplicate pointing to [2, 1, 3] (length 3…
Question
collection = []
collection.append(1)
collection.insert(0, 2)
duplicate = collection
duplicate.append(3)
print(len(collection) + len(duplicate))
Options
- AThe code raises an exception and outputs nothing.
- B4
- C5
- D6
How the community answered
(45 responses)- A2% (1)
- B9% (4)
- C18% (8)
- D71% (32)
Explanation
Option D is correct because duplicate = collection does not create a copy - it creates a second reference to the same list object in memory. So when duplicate.append(3) runs, it modifies the one shared list, leaving both collection and duplicate pointing to [2, 1, 3] (length 3 each), making 3 + 3 = 6.
- A is wrong because no exception is raised; all operations (
append,insert, assignment) are valid Python. - B (4) is wrong because it would require each list to have 2 elements - a mistake made if you assume the list only grew via
appendand forgotinsertadded an element. - C (5) is wrong because it's the trap answer for those who correctly track
collectionhaving 3 elements but mistakenly believeduplicateis a copy that only received the oneappend(3)call, giving lengths 3 + 2 = 5.
Memory tip: In Python, b = a for a list means "b points to the same list as a" - think of it as two name tags on one box. To get an independent copy, use b = a.copy() or b = a[:].
Community Discussion
No community discussion yet for this question.