nerdexam
Python_Institute

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

What is the expected output of the following code?
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)
  • A
    2% (1)
  • B
    9% (4)
  • C
    18% (8)
  • D
    71% (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 append and forgot insert added an element.
  • C (5) is wrong because it's the trap answer for those who correctly track collection having 3 elements but mistakenly believe duplicate is a copy that only received the one append(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.

Full PCEP-30-02 Practice