CBSE Class 11 Computer Science
Question 75 of 104
List Manipulation — Question 11
Back to all questions 11
Question Question 11
Predict the output of following two parts. Are the outputs same? Are the outputs different? Why?
(a)
L1, L2 = [2, 4] , [2, 4]
L3 = L2
L2[1] = 5
print(L3) (b)
L1, L2 = [2, 4] , [2, 4]
L3 = list(L2)
L2[1] = 5
print(L3)Answer
Output of part (a) is:
[2, 5]
Output of part (b) is:
[2, 4]
As we can see, outputs of the two parts are different. The reason is that in part (a), the statement L3 = L2 creates a shallow copy of L2 in L3 i.e. both the variables L2 and L3 point to the same list. Hence, when element at index 1 of L2 is changed to 5, that change is visible in L3 also. On the other hand in part (b), the statement L3 = list(L2) creates a true copy (also called deep copy) of L2 so L3 points to a different list in memory which has the same elements as L2. Now when element at index 1 of L2 is changed to 5, that change is not visible in L3.