In python, why is appending a list to a larger list, then updating one of them, also updating all the other appended lists?

Question:

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.

Asked By: ZonicTrout

||

Answers:

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)
Answered By: ykerus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.