Note that you should be careful when copying lists in Python. For more details, please search for "pass by value / pass by reference".
Look at the code below before explaining it in words.
X = 2
Y = X
Y = 5
print('Y = ', Y)
print('X = ', X)
If you do this, of course
Y = 5
X = 2
The result is obtained. Next, try running the following code.
i = [1, 2, 3, 4, 5]
j = i
j[0] = 100
print('j = ', j)
print('i = ', i)
Here, a list called i is decided, i is assigned to j, the value of index number 0 of j is set to 100, and i and j are output respectively. The result is
j = [100, 2, 3, 4, 5]
i = [100, 2, 3, 4, 5]
And i has also changed. You can see the cause of this in the following code.
print(id(X))
print(id(Y))
print(id(i))
print(id(j))
4436251808
4436251904
4304286176
4304286176
It turns out that X and Y with the assigned values have different ids, while i and j with the assigned list have the same id. Therefore, in the list, the changes made in j will be reflected in i as well. Therefore, when copying the list,
j = i.copy()
I've heard that you rarely copy lists, so I don't think you'll use them very often, but be careful not to lead to bugs.
Recommended Posts