QuestionQ273

VerifiedData Collections – Tuples, Dictionaries, Lists, and Strings

What output is expected from the following code?

Question Image

Explanation

Tracing the list operations: collection.insert(0,1) makes [1], append(2) makes [1, 2]. duplicate = collection[:] makes an independent shallow copy [1, 2]. duplicate.append(3) changes only the copy to [1, 2, 3], leaving collection as [1, 2]. Therefore collection[-1] is 2 and duplicate[-1] is 3, and 2 + 3 = 5. The key point is that slicing [:] copies the list, so appending to the copy does not affect the original.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!