2

I'm having some problems with the following code (Python):

x = [0,0]
y = [[1,1],[2,2],[3,3]]
z = y
# z = [[1,1],[2,2],[3,3]]

print(y)
for i in range(0,len(z)):
    if i == 0:
        z[i] = x
    else:
        z[i] = y[i-1]
print(y)

y = z

print(y)
for i in range(0,len(z)):
    if i == 0:
        z[i] = x
    else:
        z[i] = y[i-1]
print(y)

What I'd expect as the output is

[[1, 1], [2, 2], [3, 3]]
[[1, 1], [2, 2], [3, 3]]
[[0, 0], [1, 1], [2, 2]]
[[0, 0], [1, 1], [2, 2]]

but what I get is

[[1, 1], [2, 2], [3, 3]]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]

and when I instead use the line I commented out for z, I get

[[1, 1], [2, 2], [3, 3]]
[[1, 1], [2, 2], [3, 3]]
[[0, 0], [1, 1], [2, 2]]
[[0, 0], [0, 0], [0, 0]]

Why aren't lines 1&2 and 3&4 of the output always the same? As far as I can tell, I'm not doing anything to change y (other than y=z) and I don't understand why using z=y or z = [...] at the beginning makes a difference.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
user44557
  • 99
  • 8

2 Answers2

3

Change this line z = y to

from copy import deepcopy 

z = deepcopy(y)

Your code will work fine.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • I originally had the problem in GDscript and changed to Python to post it here because I thought I'd be more likely to get help that way. I'm more interested in knowing why I'm having the problem in the first place than it just being fixed. – user44557 Feb 20 '19 at 12:30
  • 1
    @user44557 I was editing my answer for more clarification, But the question closed, and in https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list you can find your answer better. surely the problem is assigning a list to another variable and if you change one, the other will change too. – Mehrdad Pedramfar Feb 20 '19 at 12:33
2

Because z = y sets z to point to the same object as y points to. If you then write z = [[1,1],[2,2],[3,3]], z no longer points to the same object as y, it points to a different object that has the same values.

Karl
  • 5,573
  • 8
  • 50
  • 73
  • Why does that change the second line of my output? I might just not be understanding something simple, but shouldn't `y` be the same between the first and second times I print it regardless of what `z` is? – user44557 Feb 20 '19 at 12:29
  • 1
    `y` and `z` are the same thing with different names. If you change `z`, `y` changes as well – Karl Feb 20 '19 at 12:31