-3

I am trying to update a list of Recorded Coordinates for a simple snake game. However, when I try to save the coordinates in the list, they all update to the most recent values.

I have tried setting the coordinates to a more global scale instead of inside a class file and making copies of the data I need, however none of these worked. A simple example of this is here:

my_list = []
run = True
var1 = [5, 50]
i = 0
while run and i <= 10:
    i += 1
    my_list.append(var1)
    var1[0] += 1
    var1[1] -= 1
print(my_list)

I am running python 3.11.0.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
ZonicTrout
  • 19
  • 3

1 Answers1

0

The problem is that each time you append var1 to my_list, you append a reference to the same object. If you subsequently change data in that object (i.e. by var1[0] += 1), then that has an effect on all elements of my_list. That's just how Python deals with lists. You can read more on that in other posts or you check out general Python documentation on lists.

A solution in your case could be to make a copy of the list var1 in each iteration, and append that copy to my_list. In that case, all elements of my_list will point to a different location in memory. This is achieved by simply calling .copy() on the list at hand:

my_list = []
run = True
var1 = [5, 50]
i = 0
while run and i <= 10:
    i += 1
    my_list.append(var1.copy())
    var1[0] += 1
    var1[1] -= 1
print(my_list)
chepner
  • 497,756
  • 71
  • 530
  • 681
ykerus
  • 29
  • 4
  • Note that this `.copy` works as long as var1 does not contain lists or dicts or other mutable elements, in which case you need a deepcopy. See https://stackoverflow.com/a/64104416/2745495 – Gino Mempin Jan 08 '23 at 01:22