2

I need to use a stack to push and pop lists with 2 numbers in them, that serve as XY coordinates in a program I'm making. It seems simple enough, so I just do

stack = []

to make the list I'll use as a stack. Now i make the coordinate variable

coord = [0,0]

and push it to the stack.

stack.append(coord)

Now, the stack is equal to

[[0, 0]]

and that's perfect. Now let's say I move up one, so my coord variables Y value updates like

coord[1] += 1

and coord equals

[0,1]

which is good. But wait! Even though I did nothing to the stack list, it now reads

[[0,1]]

when I wanted it to retain it's old value that I sent to it.

[[0,0]]

Why does this happen, and what can I do to accomplish what I want?

Just in case it wasn't clear, I want the stack to behave like

>>> stack = []
>>> stack
[]

>>> coord = [0,0]
>>> stack.append(coord)
>>> stack
[[0, 0]]

>>> coord[1] += 1
>>> stack
[[0, 0]]

>>> stack.append(coord)
>>> stack
[[0, 0], [0, 1]]

but this is what it does.

>>> stack = []
>>> stack
[]

>>> coord = [0,0]
>>> stack.append(coord)
>>> stack
[[0, 0]]

>>> coord[1] += 1
>>> stack
[[0, 1]]

>>> stack.append(coord)
>>> stack
[[0, 1], [0, 1]]

Changing coords[1] += 1 to coords[1] = coords[1] + 1 does not fix the problem, like it did here.

Nimaid
  • 321
  • 2
  • 3
  • 9
  • Also see [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/q/240178/4014959) and associated links. For further discussion see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by SO stalwart Ned Batchelder. – PM 2Ring Dec 27 '14 at 07:39

1 Answers1

3

You are repeatedly appending the same coords reference to stack. When you change coords, all elements of stack appear to change.

What you should do instead is append a copy of coords:

stack.append(coord[:])

The [:] makes a copy.

NPE
  • 486,780
  • 108
  • 951
  • 1,012