+ 5
In python, what happens when two lists are set as equal and you change one? Spoiler: both change. Why?
I was stumped by this question in a challenge. Please help me understand how this works. I do not understand why 'a' is changed when 'b' is changed. # Orignal code by Nabeel Gm a=[2,4,6,8] b=a b[0]=7 # a=[7,4,6,8] # b=[7,4,6,8] a[3]=9 # a=[7,4,6,9] # b=[7,4,6,9] b.append(5) # a=[7,4,6,9,5] # b=[7,4,6,9,5] print(a) print(b) # I would expect: # a=[2,4,6,9] # b=[7,4,6,8,5]
7 Answers
+ 17
If you have a list a, and assign b to a [b=a],b will point to the object a's value/address which is a list. Any changes made in b will occur to a because they refer to the same address that store's a list.
You have to assign a copy of a to b to avoid this.
[b=a.copy()]
+ 9
Yep. When you do
b = a
b is literally object a, b is merely an alias of a. You might want to read on shallow copy vs deep copy.
https://realpython.com/copying-JUMP_LINK__&&__python__&&__JUMP_LINK-objects/
+ 6
Brian M. Warner If you use the id() method you'll see that both a and b point to the same object.
id(a) == id(b)
>>>True
+ 5
Thank you! Is there a way to check or refer to this address or find the aliases?
0
I don't know,
I saw this for the first time, but Astralis' answer was so good that I learned to know
Thank you very much
0
Check this out https://youtu.be/TMWqVBmv-cc
0
when a is equal to b, and you change a, b must be changed