I have written a class to produce and manipulate a multi-dimensional list which represents a 9 x 9 grid. I have a method which produces this list. The list seems to be produced fine, but when I try to append to a specific index, it appends to all the lists.
class Grid:
def __init__(self):
self.size = range(9)
self.grid = self.make_new_grid([])
def make_new_grid(self, contents):
grid = []
for row in self.size:
grid.append([])
for column in self.size:
grid[row].append(contents)
return grid
grid = Grid()
grid.grid[4][5].append(8)
print('class grid', grid.grid)
Output:
class grid [[[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]], [[8], [8], [8], [8], [8], [8], [8], [8], [8]]]
To test this, I hardcoded the same grid and did the same. The output I got was as expected.
compare_grid = [[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []]]
compare_grid[4][5].append(8)
print(compare_grid)
Output:
comparison grid [[[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [8], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []]]
Finally I tested whether the grid produced by the class and my hardcoded grid were equal:
grid = Grid()
compare_grid = [[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []],
[[], [], [], [], [], [], [], [], []]]
print(grid.grid==compare_grid)
Output:
True
I have tried to figure this problem out for a while but I can't seem to find the answer.