Reputation: 13
I was making a rudimentary Snake game and ran into this problem. I am completely dumbfounded as to why this is happening, here is the code.
self._body is as array of arrays as such:
[[15, 20], [16, 20], [17, 20]]
The goal of this code is to make that into:
[[14, 20], [15, 20], [16, 20]]
Seems simple right? Here is the problem code, note the position of the print statements:
if move == 'w' or move == 'W' :
print(self._body)
for i in range(len(self._body)-1,0,-1):
self._body[i] = self._body[i-1]
print(self._body)
self._body[0][0] -= 1
print(self._body)
The output of this code is:
[[15, 20], [16, 20], [17, 20]]
[[15, 20], [15, 20], [16, 20]]
[[14, 20], [14, 20], [16, 20]]
It is all correct until the last statement.
for some reason,
self._body[0][0] -= 1
changes both
self._body[0][0]
and
self._body[1][0]
I cannot for the life of me figure out why. Even if I could work around I still really want to know why this happens.
Thank you so much!
Upvotes: 1
Views: 74
Reputation: 6945
Here's the problem:
self._body[i] = self._body[i-1]
This will not make a copy of the right-hand list. It will assign the exact same list object to both variables. So if you change one, you change the other. You need to make a copy of the list instead, like so:
self._body[i] = list(self._body[i-1])
This trips up a lot of people. Just remember that you have to explicitly copy lists.
Upvotes: 1