Computer Science
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.
Related Questions
Predict the output:
Odd = [1,3,5] print( (Odd +[2, 4, 6])[4] ) print( (Odd +[12, 14, 16])[4] - (Odd +[2, 4, 6])[4] )
Predict the output:
a, b, c = [1,2], [1, 2], [1, 2] print(a == b) print (a is b)
Find the errors:
- L1 = [1, 11, 21, 31]
- L2 = L1 + 2
- L3 = L1 * 2
- Idx = L1.index(45)
Find the errors:
L1 = [1, 11, 21, 31] An = L1.remove(41)