2

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]]
3
  • 2
    You should look into deepcopy... Commented May 14, 2016 at 13:49
  • @jonrsharpe thank you very much! deepcopy has solved this issue. You should post an answer to the question Commented May 14, 2016 at 13:54
  • 1
    To expound, possibilities.append(copy.deepcopy(self.board)) Commented May 14, 2016 at 13:58

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.