+ 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]

5th May 2019, 4:06 AM
Brian M. Warner
Brian M. Warner - avatar
7 odpowiedzi
+ 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()]
5th May 2019, 4:12 AM
Mensch
Mensch - avatar
+ 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/
5th May 2019, 4:14 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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
5th May 2019, 4:33 AM
Mensch
Mensch - avatar
+ 5
Thank you! Is there a way to check or refer to this address or find the aliases?
5th May 2019, 4:28 AM
Brian M. Warner
Brian M. Warner - avatar
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
6th May 2019, 3:38 AM
sweetswing2460
7th May 2019, 12:10 PM
Python Naster
0
when a is equal to b, and you change a, b must be changed
10th Jun 2019, 10:07 AM
Icant
Icant - avatar