Search code examples
pythonlistglobal-variables

Why does one global list update with the same values as another, even though they are never told to be equal?


I am trying to make a simple game of minesweeper without using OOP and have two lists: one holding the values of the table ('board[]') and one that should be empty for now ('revealed[]').

When i create an empty list of the right size in board_create() and append it to both lists the values in list 'revealed[]' change whenever I change the values in 'board[]'.

Yes, running the function for just 'revealed[]' does work but I just want to know why exactly this happens.

board = []
revealed = []
board_size = []


#creates board with size x,y
def board_create(x, y):
    global revealed
    global board
    global board_size
    board = []
    board_size = [x, y]
    for i in range(y):
        out = []
        for j in range(x):
            out.append(0)
        board.append(out)
        revealed.append(out)

board_create(3,3) would output

'board = [[0,0,0],[0,0,0],[0,0,0]]' and 'revealed = [[0,0,0],[0,0,0],[0,0,0]]' and when i change values in 'board[]' it should be

'board= [[0,1,x],[0,1,1],[0,0,0]]' (for example) and 'revealed = [[0,0,0],[0,0,0],[0,0,0]]'

not

'board= [[0,1,x],[0,1,1],[0,0,0]]' and 'revealed = [[0,1,x],[0,1,1],[0,0,0]]'


Solution

  • board.append(out)
    revealed.append(out)
    

    What you append here to board and revealed is not a copy of out, but a reference. Thus, any change you make in out by changing revealed is reflected in board. To copy out, use a slice: out[:]. See more on this topic here: Python FAQ