Leo Appleseed Leo Appleseed - 1 month ago 6
Python Question

Python updating lists error! List will not update inside while loop

grid_height = 4
grid_width = 5
cell = [0, 1]
OFFSETS = (1, 0)

col = []

while (cell[0] < grid_height) and (cell[1] < grid_width):
print cell
col.append(cell)
cell[0] += OFFSETS[0]
cell[1] += OFFSETS[1]

print col


So for this Python code, I try to get update the "cell" list and store every single new value to the list "col". However, if you run this code in Python, the value of the "cell" that is printing out is exactly the value I want to have, but when I print out "col", it just keeps repeating the value of the last, unwanted, out-of-range value of "cell". I don't think this is a scope problem as while() does not create a new scope in Python.

Please help!! It might be a really stupid mistake that I just can't find in my code!!

Answer

You appended four copies of cell to col. Note that you didn't copy the values of cell: you copied the object reference! Thus, you have four pointers to the original cell in col. Every time you update cell, the update affects each reference ... they all point to the same object.

You seem to want a copy of cell instead. Just change one line and ask for a new list:

col.append(list(cell))

Now you get the desired output:

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