1

I am trying to create a list of field states, and moves. I am doing this by appending the current field state, and move to a list. However, when I change the "field" variable and append it again, it changes all elements in the list to the most recent.

I understand I am appending a reference, but it still doesn't work when I append 'field[:]' either, which should create a copy.

Sorry for incorrect code formatting but it isn't working properly on my laptop, it has been formatted corrected in my original code

data =  []

for i in range(0,1):
field = [[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]

play = True

while play:
    compPlayed = False
    comp2Played = False

    # Loop until legal move made, which is when chosen field space = 0
    while comp2Played  == False:
        compRow2 = random.randint(0, 2)
        compCol2 = random.randint(0, 2)

        if field[compRow2][compCol2] == 0:

            # Create array containing the current field, and the legal move to be made
            gameArray = ([field,[compRow2,compCol2]])

            # Append copy to data list
            data.append(gameArray[:])
            print(data)

            # Update field and end loop
            field[compRow2][compCol2] = 1
            comp2Played = True

I expect the 'data' list to contain each field state and move made, but instead each time it appends, the field values all change to the most recent, but the moves stay that same.

>>[[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [2, 0]]] 

>>[[[[2, 0, 0], [0, 0, 0], [1, 0, 0]], [2, 0]], [[[2, 0, 0], 
  [0, 0,  0], [1, 0, 0]], [0, 2]]] 

That is an example of my output. From the first print and the second print, the field values change.

0 Answers0