Object fields in 2d array seemingly change for no reason?

Question:

I am creating a 2d array of square objects. Each square needs to be displayed in a window, so I need to iterate x and y by the width of a square and save those x and y values in the square object.

In the first nested loop it seems everything is working. Right after I create a square object and put it in the matrix, I print the row and col of the array, the x and y values where to draw the square. All results are as expected.

However when I try to access the square objects in the grid later. Every y value for every square is the same. Just the y, the x is fine.

I am printing the grid again in the same function, which should give me the same output. For some reason all of the square.y values are 12.

I want to know why all of the square.y values are becoming 12.

class Square():
    def __init__(self, row, col, x, y, value):
        #self.color = color
        self.row = row
        self.col = col
        self.x = x
        self.y = y
        self.value = value
        drawWall = False
        drawPath = False

  
SQUARE_WIDTH = 6
SQUARE_HEIGHT = 6
GRID_SIZE_HEIGHT = 3
GRID_SIZE_WIDTH = 3

def createGrid():
    print("this is the created grid n =================================================================")
    grid = [[None]* GRID_SIZE_HEIGHT] * GRID_SIZE_WIDTH
    y = 0
    for i in range(GRID_SIZE_WIDTH):
        x = 0
        for j in range(GRID_SIZE_HEIGHT):
            grid[i][j] = Square(i, j, x, y, 2)
            print(' [',i, "][", j,']:', "x", x, "y", y, end = '')
            x += SQUARE_WIDTH
        y += SQUARE_HEIGHT
        print()
        
    # printing the grid again for testing. Every y is 12
    print("============================================================")
    print("Why are all ys all 12????")
    for i in range(GRID_SIZE_WIDTH):
        for j in range(GRID_SIZE_HEIGHT):
            xr = grid[i][j].x
            yr = grid[i][j].y
            print(' [',i, "][", j,']:', "x", xr, "y", yr, end = '')
        print()
    print("====================================================")
    return grid
    
newGrid = createGrid()

Asked By: Cerberus

||

Answers:

This grid = [[None]* GRID_SIZE_HEIGHT] * GRID_SIZE_WIDTH is not a multidimensional array. It is a list in which each entry refers to one and the same list. So you have just 1 inner list that is used multiple times. You can create what you want with list comprehensions:

grid = [[None]* GRID_SIZE_HEIGHT] * GRID_SIZE_WIDTH

grid = [[None] * GRID_SIZE_HEIGHT for _ in range(GRID_SIZE_WIDTH)]
Answered By: Rabbid76
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.