robinp7720
robinp7720

Reputation: 443

Python class variable referenced from within list

As an attempt to further my knowledge in python, I have started to create a very simple tic tac toe AI.

Currently, I am stumped at some behavior I have not expected from python where when I append a class instance variable to a local list and change the item in the local list, the instance variable will have changed too.

How can I change only the local list element without affecting the class instance variable?

This is the extract of the program which is affected:

class ticAI:
    def __init__(self, board):
        self.board = board
        self.tic = tictactoe(board)

    def calc(self):
        possibilities = []
        ycord = 0
        for y in self.board:
            xcord = 0
            for x in y:
                if x == 0:
                    possibilities.append(self.board)
                    possibilities[len(possibilities)-1][ycord][xcord] = 2
                    print(self.board)
                xcord += 1
            ycord += 1

self.board looks like this:

[
    [0, 0, 0],
    [0, 1, 0],
    [0, 0, 0]
]

and outputs this:

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

it should however, output this:

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

Upvotes: 2

Views: 65

Answers (1)

robinp7720
robinp7720

Reputation: 443

As made aware by @jonrsharpe, you can use deepcopy to create a copy of a variable.

Original code:

possibilities.append(self.board)
possibilities[len(possibilities)-1][ycord][xcord] = 2
print(self.board)

New code:

b = copy.deepcopy(self.board)
possibilities.append(b)
possibilities[len(possibilities)-1][ycord][xcord] = 2
print(self.board)

Upvotes: 1

Related Questions