+ 1

Why does updating one of these two lists change the other one?

https://code.sololearn.com/cHl8T0aUJ7C7/?ref=app

9th May 2019, 6:42 PM
Benjamin Copan
Benjamin Copan - avatar
4 ответов
+ 3
in python if you need a new list to stay separate of the original you need to use the copy() method otherwise b will point to a instead of being it's own list BTW, I tested this in your code and it does solve your issue
9th May 2019, 7:14 PM
Brian Petry
Brian Petry - avatar
+ 12
Add this line at the end of your file and you'll get what happens: print(b is a)
9th May 2019, 6:48 PM
Cépagrave
Cépagrave - avatar
+ 6
as each object in python has a unique id you can check this also: print(id(a), id(b)) if you get the same number twice there is only one object but 2 variables / labels that point to it. What you have created is a shallow copy. To avoid this effect use copy. deepcopy(). Therefor you must import copy. An other way to get a deepcopy is to use the slice operator: a = [1,2,3] b = a[:]
9th May 2019, 7:17 PM
Lothar
Lothar - avatar
+ 1
Arrays are what are known as mutable. They can be changed by adding to or removing from them. When you say b=a you are doing what is called passing by reference. You aren't creating a new copy of the array and putting it in b you are literally saying that b is a reference to a. So when you change b it updates a. I'm not an expert in Python but this is how javascript does it as well. You have to write code that treats things as immutable. In other words you don't change an array, you create a new one with the same values and assign that to your new variables. In javascript we use the spread operator b = [...a]; or b=Object.assign(a); Not sure what the python equivalent is but at least this will explain what is going on. It can be a real nasty issue to solve if you are passing around array and object references through code and trying to figure out who is updating what and why.
10th May 2019, 3:58 AM
Adam
Adam - avatar