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.
Community Discussion