Python Why? Plz help to Explain line 2 & 3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python Why? Plz help to Explain line 2 & 3

a=[1,[2,3]] b=a[:] a[0]=6 a[1][1]=5 print(b)

29th Nov 2019, 12:48 AM
Storm Yule
Storm Yule - avatar
2 Answers
+ 1
You need to understand this behavior of reference type objects. (List is a reference type object.) When you use a reference type in your program, the program does not strictly handle the list self. The program handles just a reference, a link to the actual list value, the actual list value is stored somewhere else, not in the program. I don't really know how the program gets and modifies the list values when it's supposed to, but it simply does it somehow. a[:] makes copy of a, but does not use the same reference, a[:] and a are 2 different objects like you might already know. Even though b is just a copy of a, its items are original, a's changes does not affect b, but a's items' changes affect b's items.
29th Nov 2019, 1:24 AM
Seb TheS
Seb TheS - avatar
+ 1
Thank you Seb, make sense!
29th Nov 2019, 1:27 AM
Storm Yule
Storm Yule - avatar