Changing List Values | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Changing List Values

a = [1, 2, 4] b = a b[2] = 2 print(a) How is the output the first option (A)? A. [1, 2, 2] B. [1, 2, 4] a = [1, 2, 4] b = a[:] b[2] = 2 print(a) And how would the output here be the second option (B)?

11th Aug 2019, 12:39 AM
ScienceLuke7
ScienceLuke7 - avatar
1 Answer
+ 3
In the fist example, "a" and "b" are literally the same object, so any changes made to one will reflect on the other. In the second example, "a" and "b" have the same items, but they are different objects. This process (i.e. b = a[:]) is called shallow copying. https://medium.com/@thawsitt/assignment-vs-shallow-copy-vs-deep-copy-in-JUMP_LINK__&&__python__&&__JUMP_LINK-f70c2f0ebd86
11th Aug 2019, 1:08 AM
Diego
Diego - avatar