I am trying to build a game board, which is a 5x5 grid in python 2.7, presented as a 2-dimensional list. I tried to write it as board = [["O"]*cols]*rows (cols and rows are already declared as 5), but when I try to change the value in the index, it changes the whole row. for instance
cols = 5 rows = 5 board = [["O"]*cols]*rows
this prints:
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
now when i try to change the index value like:
board[1][1] = "X"
he prints:
[['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O']]
I want to change only the value in line 1 col 1.
I also tried to do the following:
board = [] for i in xrange(5): board.append(["O"]*cols)
This one works the way I want. What I want to understand, what is the difference?