+ 1

Why the assignment of b value doesn't change when a change.

Can someone explain me that when I changed the a[0] value, b[0] also changed but when I changed the entire a array, b doesn't change, why ? https://code.sololearn.com/cQ4zn2wdG15z/?ref=app

14th Oct 2020, 8:44 PM
Vishal Vashistha
Vishal Vashistha - avatar
7 Réponses
+ 2
a = [1,2,3] b =a print(id(b),id(a)) a[0] = 5 print(b[0], end = "") a = [6,7,8] print(id(a)) print (b[0], end = "") Run this and see for yourself.
14th Oct 2020, 9:51 PM
Hima
Hima - avatar
+ 3
at the beginning a and b refer to the same object,then you changed a,but b is still [5, 2, 3]
14th Oct 2020, 9:06 PM
Julia Shabanova
Julia Shabanova - avatar
+ 3
B still refers to the first object [5, 2, 3], but a refers to [6, 7, 8]
14th Oct 2020, 9:51 PM
Julia Shabanova
Julia Shabanova - avatar
+ 2
Hima , now I understand that the object id remain same as long long we modified the content of it. The moment I redefined object, the object id changed and it is no longer associated with the previous id, so it is now a new object. Thanks for help.
14th Oct 2020, 9:58 PM
Vishal Vashistha
Vishal Vashistha - avatar
+ 1
But, what about in next step. When I completely changed a, that should also changed b as well, but that doesn't happen, why ? If they belong to same object, it should be consistent.
14th Oct 2020, 9:48 PM
Vishal Vashistha
Vishal Vashistha - avatar
+ 1
I just noticed that even you redefined a value as same as earlier, this also changed the id of a. This means, we can edit the object, that doesn't change it store locations but redefining will immediately tag it to new location even though the redefined values are exactly same as earlier. https://code.sololearn.com/cQuiNk2Rh2Ln/?ref=app
14th Oct 2020, 10:05 PM
Vishal Vashistha
Vishal Vashistha - avatar
0
When you write a = something , you name something as 'a' and you can access 'something' by calling a. When you write a[0] = other , you are calling an item stored at a[0] and replacing it with other. Kinda confusing to word it I must say.
14th Oct 2020, 10:26 PM
Python Trader
Python Trader - avatar